# -*- coding: utf-8 -*-
# 请认准 VNPY官方网站 http://www.vnpy.cn
import webbrowser
import copy
import numpy as np
# K线图
import pyqtgraph as pg
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from pyqtgraph import QtCore, QtGui
from PyQt5.QtWidgets import QVBoxLayout, QWidget, QDialog, QPushButton, QMessageBox
import time
import os
import configparser
from PyQt5.QtCore import *
import globalvar
import module_strategy
import module_talib
import module_instrumentgroup
import module_backtest
import module_backtestreport
import module_combinekline
import pandas as pd
import talib as ta
import multiprocessing
from StrategyBackTestProcess import *
from StrategyProcess import *
import module_td
from datetime import timedelta
from datetime import datetime
import importlib

# K线图
global lasttime, kid
kid = 0
lasttime = -1.0


class CandlestickItem(pg.GraphicsObject):
    def __init__(self, data):
        pg.GraphicsObject.__init__(self)
        self.data = data  ## data must have fields: time, open, close, min, max
        self.generatepicture()

    def generatepicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        # print('输出A：'+str(len(self.data)))
        if len(self.data) == 0:
            pass
        elif len(self.data) == 1:
            if str(self.data) == '[(0, 0, 0, 0, 0, 0, 0)]':
                return
            else:
                w = 0.5
                for (t, tradingday, klinetime, open, close, min, max) in self.data:
                    QApplication.processEvents()
                    p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                    if open > close:
                        p.setBrush(pg.mkBrush('g'))
                    else:
                        p.setBrush(pg.mkBrush('r'))
                    p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        else:
            w = (self.data[1][0] - self.data[0][0]) / 3
            for (t, tradingday, klinetime, open, close, min, max) in self.data:
                QApplication.processEvents()
                p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                if open > close:
                    p.setBrush(pg.mkBrush('g'))
                else:
                    p.setBrush(pg.mkBrush('r'))
                p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        p.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())


# global logYdata
# pyqtgraph分时图
data_market = []
# pyqtgraph资金曲线图
data_backtest = []
# pyqtgraph实时资金曲线图
data_realtimecurve = []
# pyqtgraph K线
## 数据对应关系 (id, TradingDay, KlineTime,  open, close, min, ma).
data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
count = 0


# 对话框
class DialogOptionsWidget(QWidget):
    def __init__(self, parent=None):
        super(DialogOptionsWidget, self).__init__(parent)

    def addCheckBox(self, text, value):
        pass


class StandardDialog(QDialog):
    def __init__(self, parent=None):
        super(StandardDialog, self).__init__(parent)

        self.setWindowTitle("Standard Dialog")

        frameStyle = QFrame.Sunken | QFrame.Panel

        mainLayout = QVBoxLayout(self)
        toolbox = QToolBox()
        mainLayout.addWidget(toolbox)

        self.errorMessageDialog = QErrorMessage(self)
        pushButton_integer = QPushButton("QInputDialog.get&Int()")
        pushButton_double = QPushButton("QInputDialog.get&Double()")
        pushButton_item = QPushButton("QInputDialog.getIte&m()")
        pushButton_text = QPushButton("QInputDialog.get&Text()")
        pushButton_multiLineText = QPushButton("QInputDialog.get&MultiLineText()")
        pushButton_color = QPushButton("QColorDialog.get&Color()")
        pushButton_font = QPushButton("QFontDialog.get&Font()")
        pushButton_directory = QPushButton("QFileDialog.getE&xistingDirectory()")
        pushButton_openFileName = QPushButton("QFileDialog.get&OpenFileName()")
        pushButton_openFileNames = QPushButton("QFileDialog.&getOpenFileNames()")
        pushButton_saveFileName = QPushButton("QFileDialog.get&SaveFileName()")
        pushButton_critical = QPushButton("QMessageBox.critica&l()")
        pushButton_information = QPushButton("QMessageBox.i&nformation()")
        pushButton_question = QPushButton("QQMessageBox.&question()")
        pushButton_warning = QPushButton("QMessageBox.&warning()")
        pushButton_error = QPushButton("QErrorMessage.showM&essage()")

        self.label_integer = QLabel()
        self.label_double = QLabel()
        self.label_item = QLabel()
        self.label_text = QLabel()
        self.label_multiLineText = QLabel()
        self.label_color = QLabel()
        self.label_font = QLabel()
        self.label_directory = QLabel()
        self.label_openFileName = QLabel()
        self.label_openFileNames = QLabel()
        self.label_saveFileName = QLabel()
        self.label_critical = QLabel()
        self.label_information = QLabel()
        self.label_question = QLabel()
        self.label_warning = QLabel()
        self.label_error = QLabel()

        self.label_integer.setFrameStyle(frameStyle)
        self.label_double.setFrameStyle(frameStyle)
        self.label_item.setFrameStyle(frameStyle)
        self.label_text.setFrameStyle(frameStyle)
        self.label_multiLineText.setFrameStyle(frameStyle)
        self.label_color.setFrameStyle(frameStyle)
        self.label_font.setFrameStyle(frameStyle)
        self.label_directory.setFrameStyle(frameStyle)
        self.label_openFileName.setFrameStyle(frameStyle)
        self.label_openFileNames.setFrameStyle(frameStyle)
        self.label_saveFileName.setFrameStyle(frameStyle)
        self.label_critical.setFrameStyle(frameStyle)
        self.label_information.setFrameStyle(frameStyle)
        self.label_question.setFrameStyle(frameStyle)
        self.label_warning.setFrameStyle(frameStyle)
        self.label_error.setFrameStyle(frameStyle)

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)
        '''
        layout.addWidget(pushButton_integer, 0, 0)
        layout.addWidget(self.label_integer, 0, 1)
        layout.addWidget(pushButton_double, 1, 0)
        layout.addWidget(self.label_double, 1, 1)
        layout.addWidget(pushButton_item, 2, 0)
        layout.addWidget(self.label_item, 2, 1)
        layout.addWidget(pushButton_text, 3, 0)
        layout.addWidget(self.label_text, 3, 1)
        layout.addWidget(pushButton_multiLineText, 4, 0)
        layout.addWidget(self.label_multiLineText, 4, 1)
        '''
        layout.addWidget(pushButton_integer)
        layout.addWidget(self.label_integer)
        layout.addWidget(pushButton_double)
        layout.addWidget(self.label_double)
        layout.addWidget(pushButton_item)
        layout.addWidget(self.label_item)
        layout.addWidget(pushButton_text)
        layout.addWidget(self.label_text)
        layout.addWidget(pushButton_multiLineText)
        layout.addWidget(self.label_multiLineText)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 5, 0)
        toolbox.addItem(page, "Input Dialog")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)
        layout.addWidget(pushButton_color)
        layout.addWidget(self.label_color)
        '''
        layout.addWidget(pushButton_color, 0, 0)
        layout.addWidget(self.label_color, 0, 1)
        '''
        colorDialogOptionsWidget = DialogOptionsWidget()
        colorDialogOptionsWidget.addCheckBox("Do not use native dialog", QColorDialog.DontUseNativeDialog)
        colorDialogOptionsWidget.addCheckBox("Show alpha channel", QColorDialog.ShowAlphaChannel)
        colorDialogOptionsWidget.addCheckBox("No buttons", QColorDialog.NoButtons)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 1, 0)
        # layout.addWidget(colorDialogOptionsWidget, 2, 0, 1, 2)
        layout.addWidget(colorDialogOptionsWidget)
        toolbox.addItem(page, "Color Dialog")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        layout.addWidget(pushButton_font)
        layout.addWidget(self.label_font)
        '''
        layout.addWidget(pushButton_font, 0, 0)
        layout.addWidget(self.label_font, 0, 1)
        '''
        fontDialogOptionsWidget = DialogOptionsWidget()
        fontDialogOptionsWidget.addCheckBox("Do not use native dialog", QFontDialog.DontUseNativeDialog)
        fontDialogOptionsWidget.addCheckBox("No buttons", QFontDialog.NoButtons)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 1, 0)
        # layout.addWidget(fontDialogOptionsWidget, 2, 0, 1, 2)
        layout.addWidget(fontDialogOptionsWidget)
        toolbox.addItem(page, "Font Dialog")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        '''
        layout.addWidget(pushButton_directory, 0, 0)
        layout.addWidget(self.label_directory, 0, 1)
        layout.addWidget(pushButton_openFileName, 1, 0)
        layout.addWidget(self.label_openFileName, 1, 1)
        layout.addWidget(pushButton_openFileNames, 2, 0)
        layout.addWidget(self.label_openFileNames, 2, 1)
        layout.addWidget(pushButton_saveFileName, 3, 0)
        layout.addWidget(self.label_saveFileName, 3, 1)
        '''
        layout.addWidget(pushButton_directory)
        layout.addWidget(self.label_directory)
        layout.addWidget(pushButton_openFileName)
        layout.addWidget(self.label_openFileName)
        layout.addWidget(pushButton_openFileNames)
        layout.addWidget(self.label_openFileNames)
        layout.addWidget(pushButton_saveFileName)
        layout.addWidget(self.label_saveFileName)
        fileDialogOptionsWidget = DialogOptionsWidget()
        fileDialogOptionsWidget.addCheckBox("Do not use native dialog", QFileDialog.DontUseNativeDialog)
        fileDialogOptionsWidget.addCheckBox("Show directories only", QFileDialog.ShowDirsOnly)
        fileDialogOptionsWidget.addCheckBox("Do not resolve symlinks", QFileDialog.DontResolveSymlinks)
        fileDialogOptionsWidget.addCheckBox("Do not confirm overwrite", QFileDialog.DontConfirmOverwrite)
        fileDialogOptionsWidget.addCheckBox("Do not use sheet", QFileDialog.DontUseSheet)
        fileDialogOptionsWidget.addCheckBox("Readonly", QFileDialog.ReadOnly)
        fileDialogOptionsWidget.addCheckBox("Hide name filter details", QFileDialog.HideNameFilterDetails)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 4, 0)
        layout.addWidget(fileDialogOptionsWidget)
        toolbox.addItem(page, "File Dialogs")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        '''
        layout.addWidget(pushButton_critical, 0, 0)
        layout.addWidget(self.label_critical, 0, 1)
        layout.addWidget(pushButton_information, 1, 0)
        layout.addWidget(self.label_information, 1, 1)
        layout.addWidget(pushButton_question, 2, 0)
        layout.addWidget(self.label_question, 2, 1)
        layout.addWidget(pushButton_warning, 3, 0)
        layout.addWidget(self.label_warning, 3, 1)
        layout.addWidget(pushButton_error, 4, 0)
        layout.addWidget(self.label_error, 4, 1)
        '''
        layout.addWidget(pushButton_critical)
        layout.addWidget(self.label_critical)
        layout.addWidget(pushButton_information)
        layout.addWidget(self.label_information)
        layout.addWidget(pushButton_question)
        layout.addWidget(self.label_question)
        layout.addWidget(pushButton_warning)
        layout.addWidget(self.label_warning)
        layout.addWidget(pushButton_error)
        layout.addWidget(self.label_error)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 5, 0)
        toolbox.addItem(page, "Message Boxes")

        pushButton_integer.clicked.connect(self.setInteger)
        pushButton_double.clicked.connect(self.setDouble)
        pushButton_item.clicked.connect(self.setItem)
        pushButton_text.clicked.connect(self.setText)
        pushButton_multiLineText.clicked.connect(self.setMultiLineText)
        pushButton_color.clicked.connect(self.setColor)
        pushButton_font.clicked.connect(self.setFont)
        pushButton_directory.clicked.connect(self.setExistingDirectory)
        pushButton_openFileName.clicked.connect(self.setOpenFileName)
        pushButton_openFileNames.clicked.connect(self.setOpenFileNames)
        pushButton_saveFileName.clicked.connect(self.setsavefilename)
        pushButton_critical.clicked.connect(self.criticalmessage)
        pushButton_information.clicked.connect(self.informationmessage)
        pushButton_question.clicked.connect(self.questionmessage)
        pushButton_warning.clicked.connect(self.warningmessage)
        pushButton_error.clicked.connect(self.errormessage)

    # 输入对话框 取整数
    def setInteger(self):
        intNum, ok = QInputDialog.getInt(self, "QInputDialog.getInteger()", "Percentage:", 25, 0, 100, 1)
        if ok:
            self.label_integer.setText(str(intNum))

    # 输入对话框 取实数
    def setDouble(self):
        doubleNum, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()", "Amount:", 37.56, -10000, 10000, 2)
        if ok:
            self.label_double.setText(str(doubleNum))

    # 输入对话框 取列表项
    def setItem(self):
        items = ["Spring", "Summer", "Fall", "Winter"]
        item, ok = QInputDialog.getItem(self, "QInputDialog.getItem()", "Season:", items, 0, False)
        if ok and item:
            self.label_item.setText(item)

    # 输入对话框 取文本
    def setText(self):
        text, ok = QInputDialog.getText(self, "QInputDialog.getText()", "User name:", QLineEdit.Normal,
                                        QDir.home().dirName())
        if ok and text:
            self.label_text.setText(text)

    # 输入对话框 取多行文本
    def setMultiLineText(self):
        text, ok = QInputDialog.getMultiLineText(self, "QInputDialog.getMultiLineText()", "Address:",
                                                 "John Doe\nFreedom Street")
        if ok and text:
            self.label_multiLineText.setText(text)

    # 颜色对话框 取颜色
    def setColor(self):
        # options = QColorDialog.ColorDialogOptions(QFlag.QFlag(colorDialogOptionsWidget.value()))
        color = QColorDialog.getColor(Qt.green, self, "Select Color")
        if color.isValid():
            self.label_color.setText(color.name())
            self.label_color.setPalette(QPalette(color))
            self.label_color.setAutoFillBackground(True)

    # 字体对话框 取字体
    def setFont(self):
        # options = QFontDialog.FontDialogOptions(QFlag(fontDialogOptionsWidget.value()))
        # font, ok = QFontDialog.getFont(ok, QFont(self.label_font.text()), self, "Select Font",options)
        font, ok = QFontDialog.getFont()
        if ok:
            self.label_font.setText(font.key())
            self.label_font.setFont(font)

    # 目录对话框 取目录


def setExistingDirectory(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget->value()))
    # options |= QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
    directory = QFileDialog.getExistingDirectory(self,
                                                 "QFileDialog.getExistingDirectory()",
                                                 self.label_directory.text())
    if directory:
        self.label_directory.setText(directory)

    # 打开文件对话框 取文件名


def setOpenFileName(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
    # selectedFilter
    fileName, filetype = QFileDialog.getOpenFileName(self,
                                                     "QFileDialog.getOpenFileName()",
                                                     self.label_openFileName.text(),
                                                     "All Files (*);;Text Files (*.txt)")
    if fileName:
        self.label_openFileName.setText(fileName)

    # 打开文件对话框 取一组文件名


def setOpenFileNames(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
    # selectedFilter
    openFilesPath = "D:/documents/pyMarksix/draw/"
    files, ok = QFileDialog.getOpenFileNames(self,
                                             "QFileDialog.getOpenFileNames()",
                                             openFilesPath,
                                             "All Files (*);;Text Files (*.txt)")

    if len(files):
        self.label_openFileNames.setText(", ".join(files))

    # 保存文件对话框 取文件名


def setsavefilename(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
    # selectedFilter
    fileName, ok = QFileDialog.getSaveFileName(self,
                                               "QFileDialog.getSaveFileName()",
                                               self.label_saveFileName.text(),
                                               "All Files (*);;Text Files (*.txt)")
    if fileName:
        self.label_saveFileName.setText(fileName)


def criticalmessage(self):
    # reply = QMessageBox.StandardButton()
    MESSAGE = "批评！"
    reply = QMessageBox.critical(self,
                                 "QMessageBox.critical()",
                                 MESSAGE,
                                 QMessageBox.Abort | QMessageBox.Retry | QMessageBox.Ignore)
    if reply == QMessageBox.Abort:
        self.label_critical.setText("Abort")
    elif reply == QMessageBox.Retry:
        self.label_critical.setText("Retry")
    else:
        self.label_critical.setText("Ignore")


def informationmessage(self):
    MESSAGE = "信息"
    reply = QMessageBox.information(self, "QMessageBox.information()", MESSAGE)
    if reply == QMessageBox.Ok:
        self.label_information.setText("OK")
    else:
        self.label_information.setText("Escape")


def questionmessage(self):
    MESSAGE = "疑问"
    reply = QMessageBox.question(self, "QMessageBox.question()",
                                 MESSAGE,
                                 QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
    if reply == QMessageBox.Yes:
        self.label_question.setText("Yes")
    elif reply == QMessageBox.No:
        self.label_question.setText("No")
    else:
        self.label_question.setText("Cancel")


def warningmessage(self):
    MESSAGE = "警告文本"
    msgBox = QMessageBox(QMessageBox.Warning,
                         "QMessageBox.warning()",
                         MESSAGE,
                         QMessageBox.Retry | QMessageBox.Discard | QMessageBox.Cancel,
                         self)
    msgBox.setDetailedText("详细信息。。。")
    # msgBox.addButton("Save &Again", QMessageBox.AcceptRole)
    # msgBox.addButton("&Continue", QMessageBox.RejectRole)
    if msgBox.exec() == QMessageBox.AcceptRole:
        self.label_warning.setText("Retry")
    else:
        self.label_warning.setText("Abort")


def errormessage(self):
    self.errorMessageDialog.showMessage(
        "This dialog shows and remembers error messages. "
        "If the checkbox is checked (as it is by default), "
        "the shown message will be shown again, "
        "but if the user unchecks the box the message "
        "will not appear again if QErrorMessage.showMessage() "
        "is called with the same message.")
    self.label_error.setText("If the box is unchecked, the message "
                             "won't appear again.")


tradestate = 0
# backteststate = 0
global markettj
markettj = 0
global config


class Ui_MainWindow(object):
    '''
    def closeEvent(self, event):
        close = QMessageBox.question(self,
                                     "QUIT",
                                     "Sure?",
                                      QMessageBox.Yes | QMessageBox.No)
        if close == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def closeEvent(self, event):
        self.dlg_talibindicatrix.close()
        reply = QMessageBox.question(self, 'Message', 'Are you want to quit?', QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
            
    '''

    # self.dlg_talibindicatrix.close()

    def update_depthMarketData(self, Price, InstrumentID):
        # uimarketthread = UIUpdatemarketThread(a.contents.LastPrice)
        # uimarketthread.start()
        # uiklinethread = UIUpdateklineThread(a.contents.LastPrice)
        # uiklinethread.start()
        self.updatemarketUi(Price)
        self.updateklineUi(InstrumentID)

    global markettj

    def log_marketdata(self, mystr):
        global markettj
        markettj = markettj + 1
        if markettj > 14:
            self.list_marketdata.clear()
            markettj = 0
        _translate = QtCore.QCoreApplication.translate
        item = QtWidgets.QListWidgetItem()
        self.list_marketdata.addItem(item)
        item = self.list_marketdata.item(self.list_marketdata.count() - 1)
        tstr = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime())
        item.setText(_translate("MainWindow", tstr + mystr))

    def callback_kline(self, msg):
        pass

    def callback_td_info(self, msg):
        # 将线程的参数传入
        pass

    def callback_md_tick(self, a):
        # 将线程的参数传入
        self.log_marketdata(str(a[0], encoding="utf-8") + "%.2f" % a[1])
        # self.signal_md_tick.emit([a.contents.InstrumentID, a.contents.LastPrice, a.contents.Volume, a.contents.TradingDay, a.contents.UpdateTime, a.contents.UpdateMillisec])
        if globalvar.caompareinstrumwent(str(a[0], encoding="utf-8")):
            self.update_depthMarketData(a[1], a[0])

    def mounthyear4(self, thisdate, add):
        year = int(thisdate * 0.01)
        mounth = thisdate - year * 100
        mounth = mounth + add
        if mounth > 12:
            mounth = mounth - 12
            year = year + 1
        thisdate = year * 100 + mounth
        return thisdate

    def mounthyear3(self, thisdate, add):
        year = int(thisdate * 0.01)
        y = int(thisdate * 0.001)
        mounth = thisdate - year * 100
        mounth = mounth + add
        if mounth > 12:
            mounth = mounth - 12
            year = year + 1
        thisdate = year * 100 + mounth
        thisdate = thisdate - 1000 * y
        return thisdate

    def MakeInsutrumentID(self, instrumentMain, instrumentName, exchange, templist):
        global tempdate
        returnvalue = 0
        savedate = time.strftime("%Y%m%d", time.localtime())
        tvs = (int(float(savedate) * 0.000001)) * 1000000
        tempdate = int((float(savedate) - float(tvs)) * 0.01)
        tj = 0
        for j in range(12):
            if exchange == 'INE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'CFFEX':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'SHFE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'DCE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'CZCE':
                returnvalue = self.mounthyear3(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
        return returnvalue

    dict_period = {'K线周期: M1': '1min', 'K线周期: M3': '3min',
                   'K线周期: M5': '5min', 'K线周期: M10': '10min',
                   'K线周期: M15': '15min', 'K线周期: M30': '30min',
                   'K线周期: M60': '60min', 'K线周期: M120': '120min',
                   'K线周期: D1': '1d'
                   }

    dict_period2 = {1: '1min', 3: '3min',
                    5: '5min', 10: '10min',
                    15: '15min', 30: '30min',
                    60: '60min', 120: '120min',
                    9999001: '1d'
                    }

    dict_period3 = {'K线周期: M1': 1, 'K线周期: M3': 3,
                    'K线周期: M5': 5, 'K线周期: M10': 10,
                    'K线周期: M15': 15, 'K线周期: M30': 30,
                    'K线周期: M60': 60, 'K线周期: M120': 120,
                    'K线周期: D1': 9999001
                    }

    dict_comboBox_kline_index = {1: 0, 3: 1,
                                 5: 2, 10: 3,
                                 15: 4, 30: 5,
                                 60: 6, 120: 7,
                                 9999001: 8
                                 }

    # 从服务器获取M1周期K线数据
    def GetKlineFromeServer(self):
        global data_kline, data_market
        self.plt_kline.clear()
        data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
        globalvar.data_kline_M1.clear()
        data_market.clear()
        thisInstrument = str(globalvar.selectinstrumenid)
        try:
            # 清空该合约 DataFrame 数据
            if len(globalvar.dict_dataframe_kline_M1[thisInstrument]) > 0:
                globalvar.dict_dataframe_kline_M1[thisInstrument].drop(
                    globalvar.dict_dataframe_kline_M1[thisInstrument].index, inplace=True)
        except Exception as e:
            print("dict_dataframe_kline_M1 is empty: " + repr(e))
            globalvar.dict_dataframe_kline_M1[thisInstrument] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [], 'vol': []}, index=[])

        self.plt_kline.enableAutoRange(axis='y')
        self.plt_kline.setAutoVisible(y=False)
        # print('globalvar.thistoday: '+ str(globalvar.thistoday))
        # if globalvar.thistoday == 0:
        globalvar.thistoday = globalvar.vk.GetTradingDay()
        if globalvar.thistoday < 19000000:
            print("起始交易日错误" + str(globalvar.thistoday))
            return
        if globalvar.klineserverstate == 0:
            self.updateklineUi(globalvar.selectinstrumenid)
        elif globalvar.klineserverstate == 1:
            # 从服务器获取当日M1周期K线数据
            globalvar.vk.GetServerKline(thisInstrument, int(globalvar.thistoday))
            self.UpdateKlineUIFromFile(globalvar.selectinstrumenid, int(globalvar.thistoday))
            self.comboBox_kline.setCurrentIndex(self.dict_comboBox_kline_index[globalvar.selectperiod])
            # K线图切换到最后一次保存的周期，重新绘图
            self.ChangePeriodCharts_klineperiod(globalvar.selectperiod)
        elif globalvar.klineserverstate == 2:
            # 从服务器获取多日M1周期K线数据（需Plus会员）
            if globalvar.vk.GetServerMultiKline(thisInstrument, int(globalvar.thistoday), 10,
                                                globalvar.Plus_UserName, globalvar.Plus_Password) == 1:
                self.UpdateMultiKlineUIFromFile(globalvar.selectinstrumenid, int(globalvar.thistoday))
                globalvar.PlusAuthState = 1
                self.comboBox_kline.setCurrentIndex(self.dict_comboBox_kline_index[globalvar.selectperiod])
                # K线图切换到最后一次保存的周期，重新绘图
                self.ChangePeriodCharts_klineperiod(globalvar.selectperiod)
            else:
                webbrowser.open('http://www.vnpy.cn/qplus.html')

    # 从内存获取K线 M1周期数据
    def GetKlineFromeMemory(self, df, period_type):
        global data_kline, data_market
        self.plt_kline.clear()
        data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
        globalvar.data_kline_M1.clear()
        data_market.clear()
        thisInstrument = str(globalvar.selectinstrumenid)
        self.plt_kline.enableAutoRange(axis='y')
        self.plt_kline.setAutoVisible(y=False)
        if globalvar.thistoday == 0:
            globalvar.thistoday = globalvar.vk.GetTradingDay()
        if globalvar.thistoday < 19000000:
            print("起始交易日错误" + str(globalvar.thistoday))
            return
        self.UpdateKlineChartsBycombox(globalvar.selectinstrumenid, period_type, df)

    # 由M1周期数据，通过DataFrame方式生成选中combox 周期的K线数据，并更新K线图表
    def UpdateKlineChartsBycombox(self, InstrumentID, period_type, df):
        global data_kline_M1
        data_kline_M1 = [(0, 0, 0, 0, 0, 0, 0), ]
        try:
            cid = 1
            globalvar.ticklist = []
            for index, row in df.iterrows():
                QApplication.processEvents()
                # if lastdatetime != str(row['datetime']):
                # ld = line.split(',')
                temp = (cid,
                        float(str(row['tradingday'])),
                        float(str(row['klinetime'])),
                        float(str(row['open'])),
                        float(str(row['close'])),
                        float(str(row['low'])),
                        float(str(row['high'])))
                globalvar.data_kline_M1.append(temp)

                tempstr = str(int(float(row['klinetime']) * 10000))
                tempstr_list = list(tempstr)
                tempstr_list.insert(len(tempstr_list) - 2, ':')
                tempstr = ''.join(tempstr_list)
                globalvar.ticklist.append(str(row['tradingday']) + "\n" + tempstr)

                cid = cid + 1
            self.plt_kline.removeItem(self.item)
            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
            except Exception as e:
                print("UpdateKlineChartsBycombox Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])
            # 根据M1周期K线合成M3周期K线数据
            # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")
        except Exception as e:
            print("UpdateKlineChartsBycombox Error:" + repr(e))

    def InitKlineDataFrame(self, InstrumentID):
        try:
            if isinstance(globalvar.dict_dataframe_kline_M3[InstrumentID], pd.DataFrame):
                pass
        except Exception as e:
            globalvar.dict_dataframe_kline_M3[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M5[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M10[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M15[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M30[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M60[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M120[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_D1[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            print("InitKlineDataFrame Error:" + repr(e))

    # DataFrame数据预处理，由M1周期数据，通过DataFrame方式生成选中combox 周期的K线数据，并更新K线图表
    # 根据M1 K线数据生成多个周期的K线数据，以DataFrame格式存储在dataframe_kline目录下
    def combineklineUpdateCharts(self, InstrumentID, period_type):
        # 初始化该合约DataFrame类型的除M1周期以外所有周期的K线数据变量
        self.InitKlineDataFrame(InstrumentID)
        dict_period_dataframe_kline = {'K线周期: M1': globalvar.dict_dataframe_kline_M1[InstrumentID],
                                       'K线周期: M3': globalvar.dict_dataframe_kline_M3[InstrumentID],
                                       'K线周期: M5': globalvar.dict_dataframe_kline_M5[InstrumentID],
                                       'K线周期: M10': globalvar.dict_dataframe_kline_M10[InstrumentID],
                                       'K线周期: M15': globalvar.dict_dataframe_kline_M15[InstrumentID],
                                       'K线周期: M30': globalvar.dict_dataframe_kline_M30[InstrumentID],
                                       'K线周期: M60': globalvar.dict_dataframe_kline_M60[InstrumentID],
                                       'K线周期: M120': globalvar.dict_dataframe_kline_M120[InstrumentID],
                                       'K线周期: D1': globalvar.dict_dataframe_kline_D1[InstrumentID]
                                       }

        try:

            if not os.path.exists(("dataframe_kline\\" + InstrumentID)):
                os.mkdir("dataframe_kline\\" + InstrumentID)
            globalvar.dict_dataframe_kline_M1[InstrumentID].to_csv(
                "dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index=False)
            data = pd.read_csv("dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index_col='datetime',
                               parse_dates=True)

            grouper = data.groupby(
                [pd.Grouper(freq=period_type), 'recordid', 'tradingday', 'klinetime', 'instrumentid', 'open', 'close',
                 'low', 'high',
                 'vol'])

            df = pd.DataFrame(grouper['instrumentid'].count())
            df.rename(columns={'instrumentid': 'count'}, inplace=True)
            df.reset_index(inplace=True)
            del df['count']

            df2 = pd.DataFrame(
                {"datetime": [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [],
                 'low': [], 'high': [],
                 'vol': []}, index=[])

            lastdatetime = ""
            high = 0
            low = 0
            open = 0
            close = 0
            vol = 0
            instrumentid = ""
            datetime = ""
            tradingday = ""
            klinetime = ""
            recordid = 1

            for index, row in df.iterrows():
                QApplication.processEvents()
                if lastdatetime != str(row['datetime']):
                    if open > 0:
                        tempdata = {"datetime": datetime, "recordid": '{:0>8s}'.format(str(recordid)),
                                    "tradingday": tradingday, "klinetime": klinetime,
                                    "instrumentid": instrumentid,
                                    "open": open, "close": close, "low": low, "high": high, "vol": vol}
                        df2 = df2.append(tempdata, ignore_index=True)
                    recordid = int(row['recordid'])
                    open = float(row['open'])
                    low = float(row['low'])
                    high = float(row['high'])
                    close = float(row['close'])
                    vol = int(row['vol'])
                    lastdatetime = str(row['datetime'])
                    lastclose = row['close']
                    datetime = row['datetime']
                    instrumentid = row['instrumentid']
                    tradingday = row['tradingday']
                    klinetime = row['klinetime']
                else:
                    recordid = int(row['recordid'])
                    low = min(low, float(row['low']))
                    high = max(high, float(row['high']))
                    close = float(row['close'])
                    vol = vol + int(row['vol'])

            df2 = df2.sort_values(by='recordid')
            df2.to_csv("dataframe_kline\\" + InstrumentID + "\\kline_" + period_type + ".csv", index=True)
            dict_period_dataframe_kline[period_type] = df2.copy()

            # TALIB公式计算
            '''
            dw = pd.DataFrame()
            # KDJ 值对应的函数是 STOCH
            dw['slowk'], dw['slowd'] = ta.STOCH(df2['high'].values,
                                                df2['low'].values,
                                                df2['close'].values,
                                                fastk_period=9,
                                                slowk_period=3,
                                                slowk_matype=0,
                                                slowd_period=3,
                                                slowd_matype=0)
          
            # 求出J值，J = (3*K)-(2*D)
            dw['slowj'] = list(map(lambda x, y: 3 * x - 2 * y, dw['slowk'], dw['slowd']))
            dw.index = range(len(dw))
            print("talib: " + dw[-3:])
            '''
            # 从内存获取K线数据并更新K线图表
            self.GetKlineFromeMemory(dict_period_dataframe_kline[period_type], period_type)

        except Exception as e:
            print("combineklineUpdateCharts Error:" + repr(e))

    # 需要生成合约&周期的K线数据状态
    # 合约为dict,周期为list
    dict_instrument_period = {}

    # DataFrame数据预处理，由M1周期数据，后台方式计算，通过DataFrame方式生成选中combox 周期的K线数据，
    # 并根据M1 K线数据生成多个周期的K线数据，以DataFrame格式存储在dataframe_kline目录下
    def combineklineBackgroundCal(self, InstrumentID):
        # 初始化该合约DataFrame类型的除M1周期以外所有周期的K线数据变量
        self.InitKlineDataFrame(InstrumentID)
        dict_period_dataframe_kline = {'K线周期: M1': globalvar.dict_dataframe_kline_M1[InstrumentID],
                                       'K线周期: M3': globalvar.dict_dataframe_kline_M3[InstrumentID],
                                       'K线周期: M5': globalvar.dict_dataframe_kline_M5[InstrumentID],
                                       'K线周期: M10': globalvar.dict_dataframe_kline_M10[InstrumentID],
                                       'K线周期: M15': globalvar.dict_dataframe_kline_M15[InstrumentID],
                                       'K线周期: M30': globalvar.dict_dataframe_kline_M30[InstrumentID],
                                       'K线周期: M60': globalvar.dict_dataframe_kline_M60[InstrumentID],
                                       'K线周期: M120': globalvar.dict_dataframe_kline_M120[InstrumentID],
                                       'K线周期: D1': globalvar.dict_dataframe_kline_D1[InstrumentID]
                                       }
        try:
            if not os.path.exists(("dataframe_kline\\" + InstrumentID)):
                os.mkdir("dataframe_kline\\" + InstrumentID)
            globalvar.dict_dataframe_kline_M1[InstrumentID].to_csv(
                "dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index=False)
            data = pd.read_csv("dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index_col='datetime',
                               parse_dates=True)
            grouper = data.groupby(
                [pd.Grouper(freq=period_type), 'recordid', 'tradingday', 'klinetime', 'instrumentid', 'open', 'close',
                 'low', 'high',
                 'vol'])
            df = pd.DataFrame(grouper['instrumentid'].count())
            df.rename(columns={'instrumentid': 'count'}, inplace=True)
            df.reset_index(inplace=True)
            del df['count']
            df2 = pd.DataFrame(
                {"datetime": [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [],
                 'low': [], 'high': [],
                 'vol': []}, index=[])

            lastdatetime = ""
            high = 0
            low = 0
            open = 0
            close = 0
            vol = 0
            instrumentid = ""
            datetime = ""
            tradingday = ""
            klinetime = ""
            recordid = 1
            for index, row in df.iterrows():
                QApplication.processEvents()
                if lastdatetime != str(row['datetime']):
                    if open > 0:
                        tempdata = {"datetime": datetime, "recordid": '{:0>8s}'.format(str(recordid)),
                                    "tradingday": tradingday, "klinetime": klinetime,
                                    "instrumentid": instrumentid,
                                    "open": open, "close": close, "low": low, "high": high, "vol": vol}
                        df2 = df2.append(tempdata, ignore_index=True)
                    recordid = int(row['recordid'])
                    open = float(row['open'])
                    low = float(row['low'])
                    high = float(row['high'])
                    close = float(row['close'])
                    vol = int(row['vol'])
                    lastdatetime = str(row['datetime'])
                    lastclose = row['close']
                    datetime = row['datetime']
                    instrumentid = row['instrumentid']
                    tradingday = row['tradingday']
                    klinetime = row['klinetime']
                else:
                    recordid = int(row['recordid'])
                    low = min(low, float(row['low']))
                    high = max(high, float(row['high']))
                    close = float(row['close'])
                    vol = vol + int(row['vol'])

            df2 = df2.sort_values(by='recordid')
            df2.to_csv("dataframe_kline\\" + InstrumentID + "\\kline_" + period_type + ".csv", index=True)
            dict_period_dataframe_kline[period_type] = df2.copy()
            # 更新K线图表
            # self.UpdateKlineChartsBycombox(InstrumentID, period_type, dict_period_dataframe_kline[period_type])
            # self.GetKlineFromeMemory(dict_period_dataframe_kline[period_type],period_type)
        except Exception as e:
            print("combineklineBackgroundCal Error:" + repr(e))

    def to_comboBox_klineperiod(self, text):
        globalvar.selectperiod = self.dict_period3[text]
        print('globalvar.selectperiod: ' + str(globalvar.selectperiod))
        print('globalvar.selectinstrumenid: ' + str(globalvar.selectinstrumenid))
        print('self.dict_period[text]: ' + str(self.dict_period[text]))
        self.combineklineUpdateCharts(globalvar.selectinstrumenid, self.dict_period[text])

    def ChangePeriodCharts_klineperiod(self, period):
        self.combineklineUpdateCharts(globalvar.selectinstrumenid, self.dict_period2[period])

    def Background_klineperiod(self):
        self.combineklineBackgroundCal(globalvar.selectinstrumenid)

    def to_comboBox_1(self, text):
        self.comboBox_instrument.clear()
        self.comboBox_instrumentid.clear()
        templist = text.split(",", -1)
        # templist2 = []
        # self.MakeInsutrumentID(templist[0],templist[1],templist[2],templist2)
        # self.comboBox_instrumentid.addItems(templist2)
        if templist[0] == 'ALL':
            self.comboBox_instrument.addItems(globalvar.list_INE)
            self.comboBox_instrument.addItems(globalvar.list_CFFEX)
            self.comboBox_instrument.addItems(globalvar.list_SHFE)
            self.comboBox_instrument.addItems(globalvar.list_DCE)
            self.comboBox_instrument.addItems(globalvar.list_CZCE)
        elif templist[0] == 'INE':
            self.comboBox_instrument.addItems(globalvar.list_INE)
            if len(globalvar.list_INE) > 0:
                templist2 = globalvar.list_INE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_INE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'CFFEX':
            self.comboBox_instrument.addItems(globalvar.list_CFFEX)
            if len(globalvar.list_CFFEX) > 0:
                templist2 = globalvar.list_CFFEX[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_CFFEX[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'SHFE':
            self.comboBox_instrument.addItems(globalvar.list_SHFE)
            if len(globalvar.list_SHFE) > 0:
                templist2 = globalvar.list_SHFE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_SHFE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'DCE':
            self.comboBox_instrument.addItems(globalvar.list_DCE)
            if len(globalvar.list_DCE) > 0:
                templist2 = globalvar.list_DCE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_DCE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'CZCE':
            self.comboBox_instrument.addItems(globalvar.list_CZCE)
            if len(globalvar.list_CZCE) > 0:
                templist2 = globalvar.list_CZCE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_CZCE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        self.GetKlineFromeServer()

    def to_comboBox_2(self, text):
        self.comboBox_instrumentid.clear()
        templist = text.split(",", -1)
        templist2 = []
        self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
        self.comboBox_instrumentid.addItems(templist2)
        globalvar.selectinstrumenid = templist2[0]
        globalvar.rc.updatehistorystock(templist2[0])
        if templist[2] == 'ALL':
            self.comboBox_exchange.setCurrentText(templist[2] + ',全部交易所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'INE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',能源所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'CFFEX':
            self.comboBox_exchange.setCurrentText(templist[2] + ',中金所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'SHFE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',上期所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'DCE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',大商所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'CZCE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',郑商所')
            globalvar.selectexchange = templist[2]
        self.GetKlineFromeServer()

    def to_comboBox_3(self, text):
        globalvar.selectinstrumenid = text
        globalvar.rc.updatehistorystock(text)
        self.GetKlineFromeServer()

    def change_comboBox(self, text):
        global dict_instrument, dict_instrument
        globalvar.rc.updatehistorystock(text)
        if text in globalvar.dict_exchange:
            self.comboBox_exchange.setCurrentText(str(globalvar.dict_exchange[text]))
            self.to_comboBox_1(str(globalvar.dict_exchange[text]))
            self.comboBox_instrument.setCurrentText(str(globalvar.dict_instrument[text]))
            self.to_comboBox_2(str(globalvar.dict_instrument[text]))
            self.comboBox_instrumentid.setCurrentText(text)
            self.to_comboBox_3(text)

    def callback_md_combox(self):
        self.comboBox_instrument.addItems(globalvar.list_INE)
        self.comboBox_instrument.addItems(globalvar.list_CFFEX)
        self.comboBox_instrument.addItems(globalvar.list_SHFE)
        self.comboBox_instrument.addItems(globalvar.list_DCE)
        self.comboBox_instrument.addItems(globalvar.list_CZCE)

    def move_button(self):
        # self.Button_h1
        pass

    class DialogTradeConfirm(QtWidgets.QDialog):
        def __init__(self):
            super().__init__()
            self.InitUI()

        def Function_InsertOrder(self):
            pass
            # result = result + globalvar.td.InsertOrder(str(marketdata.contents.InstrumentID, encoding="utf-8"), exchangeid,'1', '0',VN_OPT_LimitPrice , marketdata.contents.LastPrice-10, 1)

        def InitUI(self):
            self.setWindowFlags(Qt.WindowCloseButtonHint)
            # self.btn_helper = QPushButton('选择期货公司', self)
            # self.btn_helper.move(380, 20)
            # self.btn_helper.clicked.connect(self.showDialog)
            self.label_1 = QLabel(self)
            self.label_1.setText("合约")
            self.label_1.move(60, 20)
            self.label_2 = QLabel(self)
            self.label_2.setText("方向")
            self.label_2.move(60, 55)
            self.label_3 = QLabel(self)
            self.label_3.setText("交易密码")
            self.label_3.move(60, 90)

            self.label_7 = QLabel(self)
            self.label_7.setText("输入格式 tcp://ip:port")
            self.label_7.resize(140, 30)
            self.label_7.move(380, 230)
            self.label_8 = QLabel(self)
            self.label_8.setText("APPID")
            self.label_8.move(60, 230)
            self.label_9 = QLabel(self)
            self.label_9.setText("AUTHCODE")
            self.label_9.move(60, 265)
            self.label_10 = QLabel(self)
            self.label_10.setText("ProductInfo")
            self.label_10.move(60, 300)
            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(330, 265)
            self.btn_authcode.resize(130, 30)
            self.btn_authcode.clicked.connect(self.Function_InsertOrder)
            self.Edit_brokerid = QLineEdit(self)
            self.Edit_brokerid.move(160, 20)
            self.Edit_brokerid.resize(200, 30)
            self.Edit_investor = QLineEdit(self)
            self.Edit_investor.move(160, 55)
            self.Edit_investor.resize(200, 30)
            self.Edit_password = QLineEdit(self)
            self.Edit_password.move(160, 90)
            self.Edit_password.resize(200, 30)
            self.Edit_addr1 = QLineEdit(self)
            self.Edit_addr1.move(160, 125)
            self.Edit_addr1.resize(200, 30)
            self.Edit_addr2 = QLineEdit(self)
            self.Edit_addr2.move(160, 160)
            self.Edit_addr2.resize(200, 30)
            self.Edit_addr3 = QLineEdit(self)
            self.Edit_addr3.move(160, 195)
            self.Edit_addr3.resize(200, 30)
            self.Edit_APPID = QLineEdit(self)
            self.Edit_APPID.move(160, 230)
            self.Edit_APPID.resize(150, 30)
            self.Edit_authcode = QLineEdit(self)
            self.Edit_authcode.move(160, 265)
            self.Edit_authcode.resize(150, 30)
            self.Edit_auserproductinfo = QLineEdit(self)
            self.Edit_auserproductinfo.move(160, 300)
            self.Edit_auserproductinfo.resize(150, 30)
            self.btn_ok = QPushButton('确认修改账户信息', self)
            self.btn_ok.move(150, 350)
            self.btn_ok.resize(300, 50)
            self.btn_ok.clicked.connect(self.TradeConfirm)
            self.setGeometry(500, 600, 420, 450)
            self.show()
            try:
                global config
                config = configparser.ConfigParser()
                # -read读取ini文件
                config.read('vnctptd.ini', encoding='utf-8')
                brokeid = config.get('setting', 'brokeid')
                investor = config.get('setting', 'investor')
                password = config.get('setting', 'password')
                appid = config.get('setting', 'appid')
                userproductinfo = config.get('setting', 'userproductinfo')
                authcode = config.get('setting', 'authcode')

                print('read %s %s %s' % (investor, password, appid))
                self.Edit_brokerid.setText(brokeid)
                self.Edit_investor.setText(investor)
                self.Edit_password.setText(password)
                self.Edit_APPID.setText(appid)
                self.Edit_authcode.setText(authcode)
                self.Edit_auserproductinfo.setText(userproductinfo)

            except Exception as e:
                print("initUI Error:" + repr(e))

        def TradeConfirm(self):
            global config
            config = configparser.ConfigParser()
            config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
            config.set("setting", "brokeid", self.Edit_brokerid.text())
            config.set("setting", "investor", self.Edit_investor.text())
            config.set("setting", "password", self.Edit_password.text())
            config.set("setting", "appid", self.Edit_APPID.text())
            config.set("setting", "authcode", self.Edit_authcode.text())
            config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
            config.set("setting", "address1", self.Edit_addr1.text())
            config.set("setting", "address2", self.Edit_addr2.text())
            config.set("setting", "address3", self.Edit_addr3.text())
            config.write(open("vnctptd.ini", mode="w"))
            messageBox = QMessageBox()
            messageBox.setWindowTitle('提示')
            messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
            messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messageBox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messageBox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messageBox.exec_()
            if messageBox.clickedButton() == buttonY:
                os._exit(1)
            elif messageBox.clickedButton() == buttonN:
                pass

    # Talib指标设置
    class DialogTalib(QtWidgets.QDialog):
        class DialogTalibSetting(QtWidgets.QDialog):
            def __init__(self, indicatorsname):
                super().__init__()
                self.indicatorsname = indicatorsname
                self.InitUI()

            '''
            def sync_table_double_clicked(self, index):
                column = index.column()
                row = index.row()
                self.indicatorsname = self.tableWidget.item(row, column).text()
                print("table1: " + self.name)
            '''

            def InitUI(self):
                self.setWindowIcon(QIcon(r'talib.ico'))  # 设置窗口图标
                self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
                self.tableWidget = QTableWidget()
                self.layout = QHBoxLayout()
                self.tableWidget.setRowCount(5)  # 行数
                self.tableWidget.setColumnCount(7)  # 列数
                self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自动拉伸，充满界面
                self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
                self.tableWidget.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
                self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows);  # 设置只有行选中
                self.layout.addWidget(self.tableWidget)
                # self.tableWidget.doubleClicked.connect(self.sync_table_double_clicked)
                self.setWindowTitle(
                    self.indicatorsname + '【' + module_talib.dict_talibparameter[self.indicatorsname][0][1] + '】')

                parnum = int(module_talib.dict_talibparameter[self.indicatorsname][0][0])
                parameter = ['', '', '', '', '', '']
                DEFAULTVALUE = -1
                id = 0
                for k in range(parnum):
                    if module_talib.dict_talibparameter[self.indicatorsname][2][k] != DEFAULTVALUE:
                        parameter[id] = module_talib.dict_talibparameter[self.indicatorsname][1][k]
                        id = id + 1

                self.tableWidget.setHorizontalHeaderLabels(
                    # ['状态','备注',parameter[0], parameter[1], parameter[2], parameter[3], parameter[4], parameter[5],parameter[6]])
                    ['状态', '备注', '参数1', '参数2', '参数3', '参数4', '参数5'])

                '''
                try:
                    print("table111: " + self.indicatorsname)
                    print("table222")
                    print(str(module_talib.dict_talibparameter))
                    print('查询1'+str(module_talib.dict_talibparameter[self.indicatorsname]))
                    # 输出：查询1[[0], ['cx1', 'cx2', 'cx3'], [3, 5, 10], [4, 6, 18]]
                    print('查询2'+str(module_talib.dict_talibparameter[self.indicatorsname][1]))
                    print('查询3 启动状态, ' + str(module_talib.dict_talibparameter[self.indicatorsname][0][0]))
                    print('查询4 参数组个数 ' +          str(module_talib.dict_talibparameter[self.indicatorsname][0][1]))
                    # module_talib.dict_talibparameter[self.indicatorsname][0][0]    [#启动状态 ]
                    # module_talib.dict_talibparameter[self.indicatorsname][0][1]    [#参数组个数 ]
                    # module_talib.dict_talibparameter[self.indicatorsname][1][1]    [#参数1, #参数2,..... #参数n]
                    # module_talib.dict_talibparameter[self.indicatorsname][2]    [参数组1]
                    # module_talib.dict_talibparameter[self.indicatorsname][3]    [参数组2]
                    # module_talib.dict_talibparameter[self.indicatorsname][4]    [参数组3]
                except Exception as e:
                    print("initUI Error:" + repr(e))
                '''
                self.setLayout(self.layout)
                # 参数个数
                labelpar = []

                for k in range(parnum):
                    tempparlabel = QLabel(self)
                    tempparlabel.setText(module_talib.dict_talibparameter[self.indicatorsname][1][k])
                    tempparlabel.move(60, 220 + k * 40)
                    if module_talib.dict_talibparameter[self.indicatorsname][2][k] == DEFAULTVALUE:
                        tempparlabel2 = QLabel(self)
                        tempparlabel2.setText('调用数据')
                        tempparlabel2.move(200, 220 + k * 40)
                    else:
                        EditPar = QLineEdit(self)
                        EditPar.setText(str(module_talib.dict_talibparameter[self.indicatorsname][2][k]))
                        EditPar.move(200, 220 + k * 40)
                        EditPar.resize(120, 30)
                    labelpar.append(tempparlabel)

                # if module_talib.dict_talibparameter[self.indicatorsname][3][0]:

                def function_item_clicked(self, QTableWidgetItem):
                    check_state = QTableWidgetItem.checkState()
                    row = QTableWidgetItem.row()
                    if check_state == QtCore.Qt.Checked:
                        if row not in self.delete_row:
                            self.delete_row.append(row)
                    elif check_state == QtCore.Qt.Unchecked:
                        if row in self.delete_row:
                            self.delete_row.remove(row)

                try:
                    for i in range(len(globalvar.dict_talibcondition[self.indicatorsname])):
                        # print('lid: ' + str(globalvar.dict_talibcondition[self.indicatorsname][i]))
                        item = QTableWidgetItem(' 启用该条件')
                        if globalvar.dict_talibcondition[self.indicatorsname][i][1] == 1:
                            item.setCheckState(QtCore.Qt.Checked)
                        else:
                            item.setCheckState(QtCore.Qt.Checked)
                        # item.connect(self.table_algorithmtrading, QtCore.SIGNAL("itemClicked(QTableWidgetItem*)"), self.function_item_clicked)
                        self.tableWidget.setItem(i, 0, item)
                        item = QTableWidgetItem(globalvar.dict_talibcondition[self.indicatorsname][i][2])
                        self.tableWidget.setItem(i, 1, item)
                        item = QTableWidgetItem(globalvar.dict_talibcondition[self.indicatorsname][i][3])
                        self.tableWidget.setItem(i, 2, item)
                        item = QTableWidgetItem(globalvar.dict_talibcondition[self.indicatorsname][i][4])
                        self.tableWidget.setItem(i, 3, item)
                except Exception as e:
                    print("dict_talibcondition Error:" + repr(e))

                try:
                    for i in range(len(module_talib.dict_talibparameter[self.indicatorsname][3][0])):
                        tempparlabel2 = QLabel(self)
                        EditPar = QLineEdit(self)
                        EditPar2 = QLineEdit(self)
                        tempparlabel2.setText(str(module_talib.dict_talibparameter[self.indicatorsname][3][0][0]))
                        tempparlabel2.move(60, 230 + parnum * 40)
                        EditPar.setText('>' + str(module_talib.dict_talibparameter[self.indicatorsname][3][0][1]))
                        EditPar.move(200, 230 + parnum * 40)
                        EditPar.resize(120, 30)
                        EditPar2.setText('趋势条件')
                        EditPar2.move(400, 230 + parnum * 40)
                        EditPar2.resize(120, 30)
                except Exception as e:
                    print("talib.csv格式错误 Error:" + repr(e))
                    return

                '''
                self.btn_authcode = QPushButton('如何获取授权码？', self)
                self.btn_authcode.move(330, 265)
                self.btn_authcode.resize(130, 30)
                #self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)
                '''

                self.btn_ok = QPushButton('添加指标条件', self)
                self.btn_ok.move(300, 480)
                self.btn_ok.resize(300, 50)
                self.btn_ok.clicked.connect(self.SaveCondition)
                Edit2 = QLineEdit(self)
                Edit2.setText('（该指标条件可用于组合成策略）')
                Edit2.move(360, 550)
                Edit2.resize(180, 30)

                self.setGeometry(500, 600, 420, 450)
                self.show()
                try:
                    global config
                    config = configparser.ConfigParser()
                    # -read读取ini文件
                    config.read('vnctptd.ini', encoding='utf-8')
                    brokeid = config.get('setting', 'brokeid')
                    investor = config.get('setting', 'investor')
                    password = config.get('setting', 'password')
                    appid = config.get('setting', 'appid')
                    userproductinfo = config.get('setting', 'userproductinfo')
                    authcode = config.get('setting', 'authcode')
                    address1 = config.get('setting', 'address1')
                    address2 = config.get('setting', 'address2')
                    address3 = config.get('setting', 'address3')
                    print('read %s %s %s' % (investor, password, appid))
                    self.Edit_brokerid.setText(brokeid)
                    self.Edit_investor.setText(investor)
                    self.Edit_password.setText(password)
                    self.Edit_APPID.setText(appid)
                    self.Edit_authcode.setText(authcode)
                    self.Edit_auserproductinfo.setText(userproductinfo)
                    self.Edit_addr1.setText(address1)
                    self.Edit_addr2.setText(address2)
                    self.Edit_addr3.setText(address3)
                except Exception as e:
                    print("initUI Error:" + repr(e))

            def SaveCondition(self):
                global config
                config = configparser.ConfigParser()
                config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
                config.set("setting", "brokeid", self.Edit_brokerid.text())
                config.set("setting", "investor", self.Edit_investor.text())
                config.set("setting", "password", self.Edit_password.text())
                config.set("setting", "appid", self.Edit_APPID.text())
                config.set("setting", "authcode", self.Edit_authcode.text())
                config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
                config.set("setting", "address1", self.Edit_addr1.text())
                config.set("setting", "address2", self.Edit_addr2.text())
                config.set("setting", "address3", self.Edit_addr3.text())
                config.write(open("vnctptd.ini", mode="w"))

                messageBox = QMessageBox()
                messageBox.setWindowTitle('提示')
                messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
                messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
                buttonY = messageBox.button(QMessageBox.Yes)
                buttonY.setText('确定')
                buttonN = messageBox.button(QMessageBox.No)
                buttonN.setText('取消')
                reply = messageBox.exec_()

                strlist = [self.indicatorsname, 0, "", "", ""]
                try:
                    if len(globalvar.dict_talibcondition[self.indicatorsname]) == 0:
                        pass
                except Exception as e:
                    globalvar.dict_talibcondition[self.indicatorsname] = []
                    print("Function_Buttonclicke0 Error:" + repr(e))
                globalvar.dict_talibcondition[self.indicatorsname].append(strlist)

                # if messageBox.clickedButton() == buttonY:
                #    os._exit(1)
                # elif messageBox.clickedButton() == buttonN:
                #    pass

            def showDialog(self):
                text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                                '选择期货公司:')
                if ok:
                    self.le.setText(str(text))

        def __init__(self):
            super().__init__()
            self.InitUI()

        def closeEvent(self, event):
            globalvar.DialogTalibState = False
            try:
                if self.dlg_talibindicatrixsetting:
                    self.dlg_talibindicatrixsetting.close()
            except Exception as e:
                print("DialogTalib closeEvent Error:" + repr(e))

        def sync_table_double_clicked(self, index):
            column = index.column()
            row = index.row()
            # current_item = self.tableWidget.item(row, column)
            # current_widget = self.tableWidget.cellWidget(row, column)
            # 取Talib指标名
            strs = self.tableWidget.item(row, column).text()
            print("table: " + strs)
            self.dlg_talibindicatrixsetting = self.DialogTalibSetting(strs)
            self.dlg_talibindicatrixsetting.show()
            self.dlg_talibindicatrixsetting.resize(900, 620)
            # 居中窗口
            screen = QDesktopWidget().screenGeometry()
            size = self.dlg_talibindicatrixsetting.geometry()
            self.dlg_talibindicatrixsetting.move((screen.width() - size.width()) / 2,
                                                 (screen.height() - size.height()) / 2)
            self.dlg_talibindicatrixsetting.exec_()

        def InitUI(self):
            self.setWindowIcon(QIcon(r'talib.ico'))  # 设置窗口图标
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            self.tableWidget = QTableWidget()
            self.layout = QHBoxLayout()
            # self.resize(1400, 900)
            # tableWidget = QTableWidget()
            self.tableWidget.setRowCount(200)  # 行数
            self.tableWidget.setColumnCount(5)  # 列数
            self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自动拉伸，充满界面
            # tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            self.tableWidget.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
            # tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows);  # 设置只有行选中
            self.layout.addWidget(self.tableWidget)
            # self.connect(tableWidget,  itemClicked, this, & DialogTalib::enter);

            self.tableWidget.doubleClicked.connect(self.sync_table_double_clicked)

            self.tableWidget.setHorizontalHeaderLabels(
                ['Talib指标列表', '【TALIB指标正在', '开发集成中，', '请耐心等待】', '', '',
                 ''])  # 横向标题排列，如果使用setVerticalHeaderLabels则是纵向排列标题

            # 输出Talib支持所有的函数
            '''
            li = ta.get_functions()
            for i in range(len(li)):
                item = QTableWidgetItem(str(li[i]))
                self.tableWidget.setItem(0, i, item)
                
            '''
            dict_talibgroup = ta.get_function_groups()
            '''
            try:
                print("talib 0: " + dict_talibgroup['Cycle Indicators'][0])
                print("talib 1: " + dict_talibgroup['Cycle Indicators'][1])
                print("talib 2: " + dict_talibgroup['Cycle Indicators'][2])
                print("talib 3: " + dict_talibgroup['Cycle Indicators'][3])
            except Exception as e:
                print("talib Error:" + repr(e))
            '''
            '''
            for i, v in enumerate(dict_talibgroup):
                print(str('type: '),i, str(v))
                for j in range(len(dict_talibgroup[str(v)])):
                    print("  名称：" + dict_talibgroup[str(v)][j])
            '''

            dict_talibIndicatorstype = {'Cycle Indicators': '周期指标', 'Math Operators': '数学运算符', 'Math Transform': '数学变换',
                                        'Momentum Indicators': '动量指标', 'Overlap Studies': '重叠指标',
                                        'Pattern Recognition': 'K线形态识别', 'Price Transform': '价格指标',
                                        'Statistic Functions': '统计学指标', 'Volatility Indicators': '波动性指标',
                                        'Volume Indicators': '成交量指标'}
            dict_talibIndicatorShow = {'Cycle Indicators': True, 'Math Operators': True, 'Math Transform': True,
                                       'Momentum Indicators': False, 'Overlap Studies': False,
                                       'Pattern Recognition': False, 'Price Transform': True,
                                       'Statistic Functions': True, 'Volatility Indicators': False,
                                       'Volume Indicators': False}

            item = QTableWidgetItem('双击单元格，设置指标自动交易')
            self.tableWidget.setItem(0, 0, item)

            k = 1
            for i, v in enumerate(dict_talibgroup):
                try:
                    if dict_talibIndicatorShow[str(v)]:
                        continue
                except Exception as e:
                    print("dict_talibIndicatorShow :" + repr(e))

                item = QTableWidgetItem('【' + str(v) + dict_talibIndicatorstype[str(v)] + '】')
                self.tableWidget.setItem(k, 0, item)
                k = k + 1
                for j in range(len(dict_talibgroup[str(v)])):
                    # print("  名称：" + dict_talibgroup[str(v)][j])
                    item = QTableWidgetItem(dict_talibgroup[str(v)][j])
                    self.tableWidget.setItem(k, j, item)
                k = k + len(dict_talibgroup[str(v)]) / 5 + 2

            # 输出Talib支持所有的函数
            # li2 = ta.get_function_groups()
            # for j in range(len(li2)):
            #    print(str(li2[j]))
            # print ('get_function_groups'+ str(ta.get_function_groups()))

            self.setLayout(self.layout)

        def SaveInvestor(self):
            global config
            config = configparser.ConfigParser()
            config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
            config.set("setting", "brokeid", self.Edit_brokerid.text())
            config.set("setting", "investor", self.Edit_investor.text())
            config.set("setting", "password", self.Edit_password.text())
            config.set("setting", "appid", self.Edit_APPID.text())
            config.set("setting", "authcode", self.Edit_authcode.text())
            config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
            config.set("setting", "address1", self.Edit_addr1.text())
            config.set("setting", "address2", self.Edit_addr2.text())
            config.set("setting", "address3", self.Edit_addr3.text())
            config.write(open("vnctptd.ini", mode="w"))
            messageBox = QMessageBox()
            messageBox.setWindowTitle('提示')
            messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
            messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messageBox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messageBox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messageBox.exec_()
            if messageBox.clickedButton() == buttonY:
                os._exit(1)
            elif messageBox.clickedButton() == buttonN:
                pass

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                            '选择期货公司:')
            if ok:
                self.le.setText(str(text))

    # 修改投资者账号
    class DialogInvestor(QtWidgets.QDialog):
        def __init__(self):
            super().__init__()
            self.InitUI()

        def closeEvent(self, event):
            """
            重写closeEvent方法，实现dialog窗体关闭时执行一些代码
            """
            # .button(QMessageBox::Yes)->setText("是");
            messagebox = QMessageBox()
            messagebox.setWindowTitle('提示')
            messagebox.setText('是否关闭窗口？')
            messagebox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messagebox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messagebox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messagebox.exec_()
            if messagebox.clickedButton() == buttonY:
                event.accept()
            elif messagebox.clickedButton() == buttonN:
                event.ignore()

        def Function_OpenUrl_HOWTOGETAUTHCODE(self):
            webbrowser.open('http://www.vnpy.cn/')

        def InitUI(self):
            self.setWindowFlags(Qt.WindowCloseButtonHint)
            # self.btn_helper = QPushButton('选择期货公司', self)
            # self.btn_helper.move(380, 20)
            # self.btn_helper.clicked.connect(self.showDialog)
            self.label_1 = QLabel(self)
            self.label_1.setText("期货公司编码")
            self.label_1.move(60, 20)
            self.label_2 = QLabel(self)
            self.label_2.setText("交易账户")
            self.label_2.move(60, 55)
            self.label_3 = QLabel(self)
            self.label_3.setText("交易密码")
            self.label_3.move(60, 90)
            self.label_4 = QLabel(self)
            self.label_4.setText("交易服务器1")
            self.label_4.move(60, 125)
            self.label_5 = QLabel(self)
            self.label_5.setText("交易服务器2")
            self.label_5.move(60, 160)
            self.label_6 = QLabel(self)
            self.label_6.setText("交易服务器3")
            self.label_6.move(60, 195)
            self.label_7 = QLabel(self)
            self.label_7.setText("输入格式 tcp://ip:port")
            self.label_7.resize(140, 30)
            self.label_7.move(380, 230)
            self.label_8 = QLabel(self)
            self.label_8.setText("APPID")
            self.label_8.move(60, 230)
            self.label_9 = QLabel(self)
            self.label_9.setText("AUTHCODE")
            self.label_9.move(60, 265)
            self.label_10 = QLabel(self)
            self.label_10.setText("ProductInfo")
            self.label_10.move(60, 300)
            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(330, 265)
            self.btn_authcode.resize(130, 30)
            self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)
            self.Edit_brokerid = QLineEdit(self)
            self.Edit_brokerid.move(160, 20)
            self.Edit_brokerid.resize(200, 30)
            self.Edit_investor = QLineEdit(self)
            self.Edit_investor.move(160, 55)
            self.Edit_investor.resize(200, 30)
            self.Edit_password = QLineEdit(self)
            self.Edit_password.move(160, 90)
            self.Edit_password.resize(200, 30)
            self.Edit_addr1 = QLineEdit(self)
            self.Edit_addr1.move(160, 125)
            self.Edit_addr1.resize(200, 30)
            self.Edit_addr2 = QLineEdit(self)
            self.Edit_addr2.move(160, 160)
            self.Edit_addr2.resize(200, 30)
            self.Edit_addr3 = QLineEdit(self)
            self.Edit_addr3.move(160, 195)
            self.Edit_addr3.resize(200, 30)
            self.Edit_APPID = QLineEdit(self)
            self.Edit_APPID.move(160, 230)
            self.Edit_APPID.resize(150, 30)
            self.Edit_authcode = QLineEdit(self)
            self.Edit_authcode.move(160, 265)
            self.Edit_authcode.resize(150, 30)
            self.Edit_auserproductinfo = QLineEdit(self)
            self.Edit_auserproductinfo.move(160, 300)
            self.Edit_auserproductinfo.resize(150, 30)
            self.btn_ok = QPushButton('确认修改账户信息', self)
            self.btn_ok.move(150, 350)
            self.btn_ok.resize(300, 50)
            self.btn_ok.clicked.connect(self.SaveInvestor)
            self.setGeometry(500, 600, 420, 450)
            self.show()
            try:
                global config
                config = configparser.ConfigParser()
                # -read读取ini文件
                config.read('vnctptd.ini', encoding='utf-8')
                brokeid = config.get('setting', 'brokeid')
                investor = config.get('setting', 'investor')
                password = config.get('setting', 'password')
                appid = config.get('setting', 'appid')
                userproductinfo = config.get('setting', 'userproductinfo')
                authcode = config.get('setting', 'authcode')
                address1 = config.get('setting', 'address1')
                address2 = config.get('setting', 'address2')
                address3 = config.get('setting', 'address3')
                print('read %s %s %s' % (investor, password, appid))
                self.Edit_brokerid.setText(brokeid)
                self.Edit_investor.setText(investor)
                self.Edit_password.setText(password)
                self.Edit_APPID.setText(appid)
                self.Edit_authcode.setText(authcode)
                self.Edit_auserproductinfo.setText(userproductinfo)
                self.Edit_addr1.setText(address1)
                self.Edit_addr2.setText(address2)
                self.Edit_addr3.setText(address3)
            except Exception as e:
                print("initUI Error:" + repr(e))

        def SaveInvestor(self):
            global config
            config = configparser.ConfigParser()
            config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
            config.set("setting", "brokeid", self.Edit_brokerid.text())
            config.set("setting", "investor", self.Edit_investor.text())
            config.set("setting", "password", self.Edit_password.text())
            config.set("setting", "appid", self.Edit_APPID.text())
            config.set("setting", "authcode", self.Edit_authcode.text())
            config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
            config.set("setting", "address1", self.Edit_addr1.text())
            config.set("setting", "address2", self.Edit_addr2.text())
            config.set("setting", "address3", self.Edit_addr3.text())
            config.write(open("vnctptd.ini", mode="w"))
            messageBox = QMessageBox()
            messageBox.setWindowTitle('提示')
            messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
            messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messageBox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messageBox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messageBox.exec_()
            if messageBox.clickedButton() == buttonY:
                os._exit(1)
            elif messageBox.clickedButton() == buttonN:
                pass

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip', '选择期货公司:')
            if ok:
                self.le.setText(str(text))

    # 资金曲线
    class DialogCapitalCurve(QMainWindow):
        def __init__(self):
            super().__init__()
            self.InitUI()

        def Function_OpenUrl_HOWTOGETAUTHCODE(self):
            webbrowser.open('http://www.vnpy.cn/')

        def InitUI(self):
            self.setWindowFlags(Qt.WindowCloseButtonHint)
            self.btn_helper = QPushButton('选择期货公司', self)
            self.btn_helper.move(300, 20)
            self.btn_helper.clicked.connect(self.showDialog)
            self.label_1 = QLabel(self)
            self.label_1.setText("期货公司编码")
            self.label_1.move(60, 20)
            self.label_2 = QLabel(self)
            self.label_2.setText("交易账户")
            self.label_2.move(60, 55)
            self.label_3 = QLabel(self)
            self.label_3.setText("交易密码")
            self.label_3.move(60, 90)
            self.label_4 = QLabel(self)
            self.label_4.setText("交易服务器")
            self.label_4.move(60, 125)
            self.label_4b = QLabel(self)
            self.label_4b.setText("输入格式 tcp://ip:port")
            self.label_4b.resize(140, 30)
            self.label_4b.move(300, 125)
            self.label_5 = QLabel(self)
            self.label_5.setText("APPID")
            self.label_5.move(60, 160)
            self.label_6 = QLabel(self)
            self.label_6.setText("AUTHCODE")
            self.label_6.move(60, 195)
            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(300, 195)
            self.btn_authcode.resize(130, 30)
            self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)
            self.Edit_brokerid = QLineEdit(self)
            self.Edit_brokerid.move(140, 20)
            self.Edit_brokerid.resize(150, 30)
            self.Edit_investor = QLineEdit(self)
            self.Edit_investor.move(140, 55)
            self.Edit_investor.resize(150, 30)
            self.Edit_password = QLineEdit(self)
            self.Edit_password.move(140, 90)
            self.Edit_password.resize(150, 30)
            self.Edit_addr = QLineEdit(self)
            self.Edit_addr.move(140, 125)
            self.Edit_addr.resize(150, 30)
            self.Edit_APPID = QLineEdit(self)
            self.Edit_APPID.move(140, 160)
            self.Edit_APPID.resize(150, 30)
            self.Edit_authcode = QLineEdit(self)
            self.Edit_authcode.move(140, 195)
            self.Edit_authcode.resize(150, 30)
            self.btn_ok = QPushButton('确认添加该账户', self)
            self.btn_ok.move(170, 250)
            # self.btn.clicked.connect(self.showDialog)
            self.btn_ok.clicked.connect(self.showDialog)
            self.setGeometry(300, 300, 290, 150)
            self.show()

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                            '选择期货公司:')

            if ok:
                self.le.setText(str(text))

    import pyqtgraph as pg
    from pyqtgraph.Qt import QtCore, QtGui
    import numpy as np
    # 量化回测窗口
    class DialogBackTest(QtWidgets.QDialog):
        def __init__(self, strategyname):
            super().__init__()
            # globalvar.DialogBackTestPoint = self
            self.strategyname = strategyname
            self.mainstrategyname = os.path.splitext(strategyname)[0]
            self.mainstrategyname = self.mainstrategyname.replace('strategyfile\\', "")
            self.csvstrategyname = os.path.splitext(strategyname)[0] + '.csv'
            print(self.strategyname)
            print('mainstrategyname: ' + self.mainstrategyname)
            print('csvstrategyname: ' + self.csvstrategyname)

            # CPU逻辑核心
            self.maxprocessnum = multiprocessing.cpu_count()
            # 根据参数设置计算处的任务总数
            globalvar.totaltasknum = 0
            globalvar.finishtasknum = 0
            # 回测状态
            self.backteststate = False
            self.bt = 0
            # 任务进度条列表
            self.progressbarlist = []
            self.dict_processid = {}
            # 是否显示人工选择的资金曲线
            self.selectbacktestcurl = True
            self.InitUI()

        def closeEvent(self, event):
            """
            重写closeEvent方法，实现dialog窗体关闭时执行一些代码
            """
            globalvar.DialogSetInstrumentState = False
            messagebox = QMessageBox()
            messagebox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            messagebox.setWindowTitle('提示')
            messagebox.setText('是否关闭回测窗口？\n关闭窗口后将终止所有回测进程')
            messagebox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messagebox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messagebox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messagebox.exec_()
            if messagebox.clickedButton() == buttonY:
                if globalvar.pool != 0:
                    globalvar.pool.terminate()
                    globalvar.pool.join()
                self.closestate = True
                event.accept()
            elif messagebox.clickedButton() == buttonN:
                event.ignore()

        '''
        def sync_table_double_clicked(self, index):
            column = index.column()
            row = index.row()
            self.strategyname = self.tableWidget.item(row, column).text()
            print("table1: " + self.name)
        '''

        # 扫描合约组设置
        dict_instrumentgroup = {}
        deleteButtonlist = []

        # 从文件读取合约组信息
        def ReadInstrumentIDGroupInfo(self, filename):
            grouplist = []
            with open(filename, 'r') as f:
                for line in f:
                    grouplist = line.strip('\n').split(',')
            return len(grouplist)

        def Log(self, str):
            _translate = QtCore.QCoreApplication.translate
            __sortingEnabled = self.list_backtestlog.isSortingEnabled()
            item = QtWidgets.QListWidgetItem()
            self.list_backtestlog.addItem(item)
            item = self.list_backtestlog.item(self.list_backtestlog.count() - 1)
            item.setText(_translate("MainWindow", str))

        def dynamic_import(self, module):
            return importlib.import_module(module)

        def Function_UpdateEquityCurve(self):
            # 回测窗口，双击记录显示资金曲线
            try:
                # 读取资金曲线数据文件，并更新到pyqtgraph
                self.selectbacktestcurl = False
                tempstr = self.table_right.selectedItems()[
                              1].text() + '_' + self.table_right.selectedItems()[2].text() + '_' + \
                          self.table_right.selectedItems()[
                              3].text() + '_' + self.table_right.selectedItems()[4].text() + '_' + \
                          self.table_right.selectedItems()[5].text() + '_' + \
                          self.table_right.selectedItems()[
                              6].text() + '.txt'
                filename_curl = self.table_right.selectedItems()[0].text() + '/' + tempstr
                filename_tradingrecord = self.table_right.selectedItems()[0].text() + '/tradingrecord/' + tempstr
                list_tradingday = self.AddTradingRecordShow(filename_tradingrecord)
                data_backtest = []
                data_index_buy = []
                data_value_buy = []
                data_index_sell = []
                data_value_sell = []
                index = 0
                with open(filename_curl, 'r') as f:
                    for line in f:
                        linelist = line.strip('\n').split(',')
                        data_backtest.append(float(linelist[2]))
                        index += 1
                        if len(linelist[1]) == 5:
                            linelist[1] = '0' + linelist[1]
                        for key in list_tradingday[0]:
                            if key == linelist[0] + linelist[1]:
                                data_index_buy.append(index * 0.97)
                                data_value_buy.append(float(linelist[2]) * 0.97)
                        for key in list_tradingday[1]:
                            if key == linelist[0] + linelist[1]:
                                data_index_sell.append(index * 1.03)
                                data_value_sell.append(float(linelist[2]) * 1.03)
                        '''
                        try:
                            print('_________getkey: ' + dict0[linelist[0] + linelist[1]])
                        except Exception as e:
                            pass
                        if list_tradingday[0][key] == linelist[0] + linelist[1]:
                            data_index_buy.append(index)
                            data_value_buy.append(float(linelist[2]))
                                # print('BBB Buy:' + line + ', ' + filename + ', ' + str(linelist[0] + linelist[1]))
                        for key in list_tradingday[1]:
                            #if list_tradingday[1][linelist[0] + linelist[1]]:
                            if list_tradingday[1][key] == linelist[0] + linelist[1]:
                                data_index_sell.append(index)
                                data_value_sell.append(float(linelist[2]))
                                # print('BBB Sell:' + line + ', ' + filename + ', ' + str(linelist[0] + linelist[1]))
                        '''

                self.curve_realtime.setData(np.hstack(data_backtest))
                self.curve_buy.setData(np.hstack(data_index_buy),
                                       np.hstack(data_value_buy))
                self.curve_sell.setData(np.hstack(data_index_sell),
                                        np.hstack(data_value_sell))

            except Exception as e:
                pass

        def Function_UpdateEquityCurveByFileName(self, filename, list_tradingday):
            # 读取资金曲线数据文件，并更新到pyqtgraph
            try:
                data_backtest = []
                data_index_buy = []
                data_value_buy = []
                data_index_sell = []
                data_value_sell = []
                index = 0
                with open(filename, 'r') as f:
                    for line in f:
                        linelist = line.strip('\n').split(',')
                        data_backtest.append(float(linelist[2]))
                        if len(linelist[1]) == 5:
                            linelist[1] = '0' + linelist[1]
                        index += 1
                        if len(linelist[1]) == 5:
                            linelist[1] = '0' + linelist[1]
                        if 0:
                            for key in list_tradingday[0]:
                                if key == linelist[0] + linelist[1]:
                                    data_index_buy.append(index * 0.98)
                                    data_value_buy.append(float(linelist[2]) * 0.98)
                            for key in list_tradingday[1]:
                                if key == linelist[0] + linelist[1]:
                                    data_index_sell.append(index * 1.02)
                                    data_value_sell.append(float(linelist[2]) * 1.02)

                        '''
                        if list_tradingday[0][linelist[0] + linelist[1]]:
                            data_index_buy.append(index)
                            data_value_buy.append(float(linelist[2]))
                            print('BBB Buy:' + line + ', ' + filename + ', ' + str(linelist[0] + linelist[1]))
                        if list_tradingday[1][linelist[0] + linelist[1]]:
                            data_index_sell.append(index)
                            data_value_sell.append(float(linelist[2]))
                            print('BBB Sell:' + line + ', ' + filename + ', ' + str(linelist[0] + linelist[1]))
                        index += 1
                        '''

                self.curve_realtime.setData(np.hstack(data_backtest))
                self.curve_buy.setData(np.hstack(data_index_buy),
                                       np.hstack(data_value_buy))
                self.curve_sell.setData(np.hstack(data_index_sell),
                                        np.hstack(data_value_sell))
            except Exception as e:
                pass

        def Function_ReadInstrumentEquityCurve(self):
            instrumentfilename = self.table_righttop.selectedItems()[0].text()
            print('instrumentfilename: ' + instrumentfilename)
            pathlist = self.table_righttop.selectedItems()[0].text().split('/')
            indexfilename = 'backtestreport/' + self.mainstrategyname + '/' + pathlist[0] + '/resultlist.csv'
            if not os.path.exists(indexfilename):
                print("[%s] File does not exist" % indexfilename)
                return

            indexfilename2 = indexfilename.replace("resultlist.csv", "")
            strlist = indexfilename2.split("/")
            titlepath = strlist[0] + '/' + strlist[1] + '/' + instrumentfilename + '/'
            ui_demo = globalvar.ui.DialogFinishResult(titlepath, indexfilename)
            ui_demo.setWindowTitle('回测结果：' + titlepath)
            # ui_demo.centralWidget()
            # 居中窗口
            screen = QDesktopWidget().screenGeometry()
            size = ui_demo.geometry()
            ui_demo.move((screen.width() - size.width()) / 2,
                         (screen.height() - size.height()) / 2)
            ui_demo.show()
            ui_demo.resize(1024, 600)
            # self.childwidget = self.childwidget(self)
            ui_demo.exec_()

        # 删除勾选的记录
        def function_delete_select(self, QTableWidgetItem):
            check_state = QTableWidgetItem.checkState()
            row = QTableWidgetItem.row()
            if check_state == QtCore.Qt.Checked:
                if row not in self.delete_row:
                    self.delete_row.append(row)
            elif check_state == QtCore.Qt.Unchecked:
                if row in self.delete_row:
                    self.delete_row.remove(row)

        # 删除按钮行的记录
        def Function_delete_clicked(self, arg):
            # button = self.MainWindow.sender()
            button = self.sender()

            if button:
                row = self.table_righttop.indexAt(button.pos()).row()
                self.table_righttop.removeRow(row)

        def Function_ReadInstrumentEquityCurveForButton(self):
            button = self.sender()
            if button:
                row = self.table_righttop.indexAt(button.pos()).row()
            instrumentfilename = self.table_righttop.item(row, 0).text()
            print('instrumentfilename' + instrumentfilename)
            pathlist = instrumentfilename.split('/')
            indexfilename = 'backtestreport/' + self.mainstrategyname + '/' + pathlist[0] + '/resultlist.csv'
            if not os.path.exists(indexfilename):
                print("[%s] File does not exist" % indexfilename)
                return
            indexfilename2 = indexfilename.replace("resultlist.csv", "")
            strlist = indexfilename2.split("/")
            titlepath = strlist[0] + '/' + strlist[1] + '/' + instrumentfilename + '/'
            ui_demo = globalvar.ui.DialogFinishResult(titlepath, indexfilename)
            ui_demo.setWindowTitle('回测结果：' + titlepath)
            # ui_demo.centralWidget()
            # 居中窗口
            screen = QDesktopWidget().screenGeometry()
            size = ui_demo.geometry()
            ui_demo.move((screen.width() - size.width()) / 2,
                         (screen.height() - size.height()) / 2)
            ui_demo.show()
            ui_demo.resize(1024, 600)
            # self.childwidget = self.childwidget(self)
            ui_demo.exec_()

        def InitUI(self):
            self.setWindowIcon(QIcon(r'setinstrument.ico'))  # 设置窗口图标
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            self.setWindowFlags(QtCore.Qt.Widget)
            self.layout = QHBoxLayout()
            self.table_lefttop = QtWidgets.QTableWidget()
            self.table_lefttop.setObjectName("table_lefttop")
            self.table_lefttop.verticalHeader().setVisible(True)  # 隐藏垂直表头
            self.table_lefttop.horizontalHeader().setVisible(True)  # 隐藏水平表头
            self.table_lefttop.setColumnCount(4)
            self.table_lefttop.setRowCount(0)
            self.table_lefttop.setEditTriggers(QTableView.NoEditTriggers)
            self.table_lefttop.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.table_lefttop.setHorizontalHeaderLabels(
                ['参数', '开始', '结束', '步长'])
            # self.table_lefttop.doubleClicked.connect(self.Function_doubleClicked_strategy)
            self.table_lefttop.setColumnWidth(0, 100)
            self.table_lefttop.setColumnWidth(1, 50)
            self.table_lefttop.setColumnWidth(2, 50)
            self.table_lefttop.setColumnWidth(3, 50)
            self.table_lefttop.setRowHeight(0, 23)
            # self.table_lefttop.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自动拉伸，充满界面
            self.table_lefttop.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            self.table_lefttop.setEditTriggers(QTableView.AllEditTriggers)  # 可编辑

            self.table_leftbottom = QtWidgets.QTableWidget()
            self.table_leftbottom.setObjectName("table_leftbottom")
            self.table_leftbottom.verticalHeader().setVisible(True)  # 隐藏垂直表头
            self.table_leftbottom.horizontalHeader().setVisible(True)  # 隐藏水平表头
            self.table_leftbottom.setColumnCount(5)
            self.table_leftbottom.setRowCount(0)
            self.table_leftbottom.setEditTriggers(QTableView.NoEditTriggers)
            self.table_leftbottom.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.table_leftbottom.setHorizontalHeaderLabels(
                ['', '回测合约', '开始', '结束', '大小'])  # 设置表头文字
            self.table_leftbottom.setRowHeight(0, 28)
            self.table_leftbottom.setColumnWidth(0, 0)
            self.table_leftbottom.setColumnWidth(1, 130)
            self.table_leftbottom.setColumnWidth(2, 80)
            self.table_leftbottom.setColumnWidth(3, 80)
            self.table_leftbottom.setColumnWidth(4, 80)
            self.table_leftbottom.setSelectionMode(QAbstractItemView.NoSelection)  # 设置只能选中一行
            module_backtest.Function_ReadDataList(self.table_leftbottom, True)

            # --------------------------------Tab Begin------------------------------------
            MainWindow = self
            self.centralwidget = QtWidgets.QWidget(MainWindow)
            self.centralwidget.setObjectName("centralwidget")

            _translate = QtCore.QCoreApplication.translate

            self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.centralwidget)
            self.verticalLayout_5.setObjectName("verticalLayout_5")

            self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
            self.tabWidget.setTabPosition(QtWidgets.QTabWidget.East)
            self.tabWidget.setTabsClosable(True)
            self.tabWidget.setObjectName("tabWidget")
            self.tab_A = QtWidgets.QWidget()
            self.tab_A.setObjectName("tab_A")
            self.tab_B = QtWidgets.QWidget()
            self.tab_B.setObjectName("tab_B")
            self.tab_1 = QtWidgets.QWidget()
            self.tab_1.setObjectName("tab_1")
            self.tab_2 = QtWidgets.QWidget()
            self.tab_2.setObjectName("tab_2")
            self.tab_3 = QtWidgets.QWidget()
            self.tab_3.setObjectName("tab_3")
            self.tab_4 = QtWidgets.QWidget()
            self.tab_4.setObjectName("tab_4")
            self.page = QtWidgets.QWidget()
            self.page.setGeometry(QtCore.QRect(0, 0, 98, 44))
            self.page.setObjectName("page")
            self.page_2 = QtWidgets.QWidget()
            self.page_2.setGeometry(QtCore.QRect(0, 0, 697, 210))
            self.page_2.setObjectName("page_2")
            self.gridLayout_A = QtWidgets.QGridLayout(self.tab_A)
            self.gridLayout_A.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_A.setObjectName("gridLayout_A")
            self.gridLayout_B = QtWidgets.QGridLayout(self.tab_B)
            self.gridLayout_B.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_B.setObjectName("gridLayout_B")
            '''
            self.gridLayout_4 = QtWidgets.QGridLayout(self.page)
            self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_4.setObjectName("gridLayout_4")
            self.gridLayout_5 = QtWidgets.QGridLayout(self.page_2)
            self.gridLayout_5.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_5.setObjectName("gridLayout_5")
            '''
            self.gridLayout_1 = QtWidgets.QGridLayout(self.tab_1)
            self.gridLayout_1.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_1.setObjectName("gridLayout_1")
            self.gridLayout_2 = QtWidgets.QGridLayout(self.tab_2)
            self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_2.setObjectName("gridLayout_2")
            self.gridLayout_3 = QtWidgets.QGridLayout(self.tab_3)
            self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_3.setObjectName("gridLayout_3")
            self.gridLayout_4 = QtWidgets.QGridLayout(self.tab_4)
            self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
            self.gridLayout_4.setObjectName("gridLayout_4")
            '''
            self.listWidget = QtWidgets.QListWidget(self.page_2)
            self.listWidget.setObjectName("listWidget")
            item = QtWidgets.QListWidgetItem()
            self.listWidget.addItem(item)
            item = QtWidgets.QListWidgetItem()
            self.listWidget.addItem(item)
            item = QtWidgets.QListWidgetItem()
            self.listWidget.addItem(item)
            '''
            # self.gridLayout_5.addWidget(self.listWidget, 0, 0, 1, 1)
            self.tabWidget_A = QtWidgets.QTabWidget(self.tab_A)
            self.tabWidget_A.setObjectName("tabWidget_A")

            self.table_right = QtWidgets.QTableWidget(self.tab_1)
            self.table_right.setObjectName("table_result")
            self.table_right.setColumnCount(13)
            self.table_right.setRowCount(0)
            self.table_right.setEditTriggers(QTableView.NoEditTriggers)
            self.table_right.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.table_right.setHorizontalHeaderLabels(
                ['', '参数1', '参数2', '参数3', '参数4', '参数5', '参数6', '权益', '收益率', '胜率', '盈亏比', '交易次数', '夏普率'])
            # self.tableWidget.doubleClicked.connect(self.Function_doubleClicked_strategy)
            self.table_right.setRowHeight(0, 28)
            self.table_right.setColumnWidth(0, 0)
            self.table_right.setColumnWidth(1, 40)
            self.table_right.setColumnWidth(2, 40)
            self.table_right.setColumnWidth(3, 40)
            self.table_right.setColumnWidth(4, 40)
            self.table_right.setColumnWidth(5, 40)
            self.table_right.setColumnWidth(6, 40)
            self.table_right.setColumnWidth(7, 90)
            self.table_right.setColumnWidth(8, 85)
            self.table_right.setColumnWidth(9, 85)
            self.table_right.setColumnWidth(10, 85)
            self.table_right.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            self.table_right.clicked.connect(self.Function_UpdateEquityCurve)
            self.table_right.doubleClicked.connect(self.Function_UpdateEquityCurve)
            self.gridLayout_1.addWidget(self.table_right, 0, 0, 1, 1)

            self.checkableButton = QtWidgets.QPushButton(self.tab_2)
            self.checkableButton.setCheckable(True)
            self.checkableButton.setChecked(True)
            self.checkableButton.setObjectName("checkableButton")
            self.gridLayout_2.addWidget(self.checkableButton, 1, 0, 1, 1)
            self.gridLayout_A.addWidget(self.tabWidget_A, 0, 0, 1, 1)

            self.tabWidget.addTab(self.tab_A, "")
            self.tabWidget.addTab(self.tab_B, "")
            self.tabWidget_A.addTab(self.tab_1, "")
            self.tabWidget_A.addTab(self.tab_2, "")
            self.tabWidget_A.addTab(self.tab_3, "")
            self.tabWidget_A.addTab(self.tab_4, "")

            self.verticalLayout_5.addWidget(self.tabWidget)
            self.tabWidget.setCurrentIndex(0)
            self.tabWidget_A.setCurrentIndex(0)
            # MainWindow.setTabOrder(self.tabWidget_2, self.table_right)
            self.tabWidget_A.setTabText(self.tabWidget_A.indexOf(self.tab_1), _translate("MainWindow", "当前回测参数组"))
            self.tabWidget_A.setTabText(self.tabWidget_A.indexOf(self.tab_2), _translate("MainWindow", "当前参数组总体分析"))
            self.tabWidget_A.setTabText(self.tabWidget_A.indexOf(self.tab_3), _translate("MainWindow", "当前资金曲线对比"))
            self.tabWidget_A.setTabText(self.tabWidget_A.indexOf(self.tab_4), _translate("MainWindow", "当前回测数据K线图"))

            self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_A), _translate("MainWindow", "量化回测"))
            self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_B), _translate("MainWindow", "数据下载管理"))
            '''
            __sortingEnabled = self.listWidget.isSortingEnabled()
            self.listWidget.setSortingEnabled(False)
            item = self.listWidget.item(0)
            item.setText(_translate("MainWindow", "New Item"))
            item = self.listWidget.item(1)
            item.setText(_translate("MainWindow", "New Item"))
            item = self.listWidget.item(2)
            item.setText(_translate("MainWindow", "New Item"))

            self.listWidget.setSortingEnabled(__sortingEnabled)
            self.checkableButton.setText(_translate("MainWindow", "Checkable button"))
            '''
            # --------------------------------Tab END------------------------------------

            self.table_middle = QtWidgets.QTableWidget()
            self.table_middle.setObjectName("table_middle")
            self.table_middle.verticalHeader().setVisible(True)  # 隐藏垂直表头
            self.table_middle.horizontalHeader().setVisible(True)  # 隐藏水平表头
            self.table_middle.setColumnCount(7)
            self.table_middle.setRowCount(0)
            self.table_middle.setEditTriggers(QTableView.NoEditTriggers)
            self.table_middle.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.table_middle.setHorizontalHeaderLabels(['日期', '时间', '合约', '买卖', '开平', '成交价格', '委托手数'])
            self.table_middle.setRowHeight(0, 30)
            self.table_middle.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            self.table_middle.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            self.table_righttop = QtWidgets.QTableWidget()
            self.table_righttop.setObjectName("table_righttop")
            self.table_righttop.verticalHeader().setVisible(True)  # 隐藏垂直表头
            self.table_righttop.horizontalHeader().setVisible(True)  # 隐藏水平表头
            self.table_righttop.setColumnCount(3)
            # self.table_righttop.setRowCount(0)
            self.table_righttop.setColumnWidth(0, 200)
            self.table_righttop.setColumnWidth(1, 120)
            self.table_righttop.setColumnWidth(2, 45)
            self.table_righttop.setEditTriggers(QTableView.NoEditTriggers)
            self.table_righttop.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.table_righttop.setHorizontalHeaderLabels(['完成回测的合约', '完成时间', '操作'])
            self.table_righttop.setRowHeight(0, 30)
            # self.table_righttop.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            self.table_righttop.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            self.table_righttop.doubleClicked.connect(self.Function_ReadInstrumentEquityCurve)

            # 行情走势图
            '''
            self.winmarket = pg.GraphicsLayoutWidget(show=True)
            self.winmarket.setWindowTitle('行情走势')
            self.plt_market = self.winmarket.addPlot(title="行情走势")
            # plt_market.setAutoVisibleOnly(y=True)
            self.curve_market = self.plt_market.plot()
            self.plt_market.setMouseEnabled(x=False, y=False)  # 禁用轴操作
            # self.verticalLayout.addWidget(self.winmarket)
            self.winmarket.showMaximized()
            '''
            # 行情走势图

            # 资金曲线图
            self.wincurl = pg.GraphicsLayoutWidget(show=True, size=(400, 250))
            self.wincurl.setWindowTitle('回测资金曲线')
            self.plt_realtime = self.wincurl.addPlot(title="回测资金曲线")
            # self.wincurl.setBackground('y')
            # plt_realtime.setAutoVisibleOnly(y=True)
            self.curve_realtime = self.plt_realtime.plot(pen='y')
            self.curve_buy = self.plt_realtime.plot(x=[], y=[], pen='r', name='买入', symbolBrush=(255, 0, 0), )
            self.curve_sell = self.plt_realtime.plot(x=[], y=[], pen='g', name='卖出', symbolBrush=(0, 255, 0))
            # self.curve_point = self.plt_realtime.plot(100,pen='r')
            # data = ts.get_hist_data('sh', start='2017-10-01', end='2017-12-01').sort_index()
            # data = {'open':3000,'close':4000}
            # xdict = dict(enumerate(data.index))
            # self.plt_realtime.plot(x=list(xdict.keys()), y=data['open'].values, pen='r', name='开盘指数', symbolBrush=(255, 0, 0), )
            # self.plt_realtime.plot(x=list(xdict.keys()), y=data['close'].values, pen='g', name='收盘指数', symbolBrush=(0, 255, 0))

            self.plt_realtime.setMouseEnabled(x=False, y=False)  # 禁用轴操作
            self.wincurl.showMaximized()
            # 资金曲线图
            self.tab_tableWidget = QtWidgets.QWidget()
            self.tab_tableWidget.setObjectName("tab_tableWidget")
            self.list_backtestlog = QtWidgets.QListWidget(self.tab_tableWidget)
            self.list_backtestlog.setObjectName("list_backtestlog")
            _translate = QtCore.QCoreApplication.translate
            __sortingEnabled = self.list_backtestlog.isSortingEnabled()
            self.list_backtestlog.setSortingEnabled(False)
            self.list_backtestlog.setSortingEnabled(__sortingEnabled)
            self.layout = QtWidgets.QGridLayout(self.tab_tableWidget)
            self.layout.setContentsMargins(0, 0, 0, 0)
            self.layout.setObjectName("layout")
            # 合约任务进度条
            self.taskinstrumentIDBar = QtWidgets.QProgressBar()
            self.taskinstrumentIDBar.setProperty("taskinstrumentIDBar", 0)
            self.taskinstrumentIDBar.setObjectName("taskinstrumentIDBar")
            self.taskinstrumentIDBar.setProperty("value", '0')
            self.taskinstrumentIDBar.setFormat('完成 0%（已完成回测合约数/总合约数 = 0/' + str(self.table_leftbottom.rowCount()) + '）')

            # 合约文件载入进度
            self.taskdataBar = QtWidgets.QProgressBar()
            self.taskdataBar.setProperty("taskdataBar", 0)
            self.taskdataBar.setObjectName("taskdataBar")
            self.taskdataBar.setProperty("value", '0')
            self.taskdataBar.setFormat('数据载入进度 0%')
            # 总任务（参数组）进度条
            self.taskprogressBar = QtWidgets.QProgressBar()
            self.taskprogressBar.setProperty("taskprogressBar", 0)
            self.taskprogressBar.setObjectName("taskprogressBar")
            self.comBox_period = QtWidgets.QComboBox()
            self.comBox_period.addItems(['M1', 'M3', 'M5', 'M10', 'M15', 'M30', 'M60', 'M120'])
            self.comBox_period.setCurrentIndex(1)
            self.comBox_slippoint = QtWidgets.QComboBox()
            self.comBox_slippoint.addItems(
                ['滑点按价格1跳', '滑点按价格2跳', '滑点按价格3跳', '滑点按价格4跳', '滑点按价格5跳', '滑点按价格6跳', '滑点按价格7跳', '滑点按价格8跳'])
            self.comBox_slippoint.setCurrentIndex(0)
            self.comBox_process = QtWidgets.QComboBox()
            for k in range(self.maxprocessnum):
                self.comBox_process.addItems(['使用 ' + str(k + 1) + ' 个回测进程'])
            self.comBox_process.setCurrentIndex(self.maxprocessnum - 1)
            self.comBox_adjustment = QtWidgets.QComboBox()
            self.comBox_adjustment.addItems(
                ['不复权', '前复权', '后复权'])
            self.comBox_adjustment.setCurrentIndex(1)
            module = self.dynamic_import('strategyfile.' + self.mainstrategyname)
            self.parnum = len(module.parlist)
            for i in range(self.parnum):
                print("序号：%s   值：%s" % (i + 1, module.parlist[i]))
                self.table_lefttop.insertRow(i)
                # item = QTableWidgetItem('参数' + str(i + 1))
                item = QTableWidgetItem(module.parlist[i][0])
                item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.table_lefttop.setItem(i, 0, item)
                item = QTableWidgetItem(str(module.parlist[i][1]))
                self.table_lefttop.setItem(i, 1, item)
                item = QTableWidgetItem(str(module.parlist[i][2]))
                self.table_lefttop.setItem(i, 2, item)
                item = QTableWidgetItem(str(module.parlist[i][3]))
                self.table_lefttop.setItem(i, 3, item)

            list_tj = ["参数条件：不设置"]
            for i in range(self.parnum):
                for j in range(self.parnum):
                    if i != j:
                        if i < j:
                            temp = '参数条件：参数' + str(i + 1) + '<参数' + str(j + 1)
                        else:
                            temp = '参数条件：参数' + str(j + 1) + '>参数' + str(i + 1)
                        list_tj.append(temp)

            self.comBox_conditions0 = QtWidgets.QComboBox()
            self.comBox_conditions1 = QtWidgets.QComboBox()
            self.comBox_conditions2 = QtWidgets.QComboBox()
            dict_comboxconditions = {0: self.comBox_conditions0, 1: self.comBox_conditions1, 2: self.comBox_conditions2}
            for i in range(min(3, self.parnum - 1)):
                print('i：' + str(i))
                dict_comboxconditions[i].addItems(list_tj)
                dict_comboxconditions[i].setCurrentIndex(0)
            self.btn_ok = QPushButton('', self)

            # 更新数据显示进程
            self.btn_ok.clicked.connect(self.OnStart_BackTest)
            self.btn_ok.setSizePolicy(
                QtGui.QSizePolicy.Preferred,
                QtGui.QSizePolicy.Expanding)
            self.btn_ok.setStyleSheet("QPushButton{border-image: url(onstartbacktest1.png)}")
            self.btn_ok.setContentsMargins(0, 0, 0, 0)
            self.btn_selectall = QPushButton('选择全部', self)
            self.btn_selectclearall = QPushButton('清除全部', self)

            # self.btn_downloaddata = QPushButton('下载数据', self)
            self.btn_openprocesswindow = QPushButton('显示回测进程窗口', self)
            self.btn_closeprocesswindow = QPushButton('隐藏回测进程窗口', self)

            self.btn_openkline = QPushButton('打开回测数据样本K线图', self)
            self.btn_analysisreport = QPushButton('参数组分析报告', self)
            self.btn_selectall.clicked.connect(self.OnSelectall)
            self.btn_selectclearall.clicked.connect(self.OnSelectclearall)
            # self.btn_downloaddata.clicked.connect(self.OnDownloadData)
            self.btn_openprocesswindow.clicked.connect(self.OnOpenProcesswindow)
            self.btn_closeprocesswindow.clicked.connect(self.OnCloseProcesswindow)
            self.btn_analysisreport.clicked.connect(self.OnOpenParAnalysisReport)

            self.layout.addWidget(self.table_lefttop, 0, 0, 896, 20)
            self.layout.addWidget(self.comBox_period, 896, 0, 4, 20)
            self.layout.addWidget(self.comBox_slippoint, 900, 0, 4, 20)
            self.layout.addWidget(self.comBox_process, 904, 0, 4, 20)
            self.layout.addWidget(self.comBox_adjustment, 908, 0, 4, 20)
            self.layout.addWidget(self.table_leftbottom, 912, 0, 884, 20)
            self.layout.addWidget(self.btn_selectall, 1796, 2, 4, 8)
            self.layout.addWidget(self.btn_selectclearall, 1796, 10, 4, 8)
            # self.layout.addWidget(self.btn_downloaddata, 1796, 2, 4, 16)
            self.layout.addWidget(self.btn_ok, 1800, 0, 200, 20)
            for i in range(min(3, self.parnum - 1)):
                self.layout.addWidget(dict_comboxconditions[i], 1, 20 + 7 * i, 3, 7)
            self.layout.addWidget(self.centralwidget, 4, 20, 1466, 45)
            self.layout.addWidget(self.taskinstrumentIDBar, 1470, 20, 10, 45)
            self.layout.addWidget(self.taskdataBar, 1480, 20, 10, 45)
            self.layout.addWidget(self.taskprogressBar, 1490, 20, 10, 45)
            self.checkbox_curlsetting = QCheckBox('双击记录显示交易信号', self)
            self.layout.addWidget(self.checkbox_curlsetting, 1500, 20, 10, 5)
            self.layout.addWidget(self.btn_openprocesswindow, 1500, 25, 10, 6)
            self.layout.addWidget(self.btn_closeprocesswindow, 1500, 31, 10, 6)
            self.layout.addWidget(self.btn_openkline, 1500, 37, 10, 14)
            self.layout.addWidget(self.btn_analysisreport, 1500, 51, 10, 14)
            self.layout.addWidget(self.wincurl, 1510, 20, 490, 45)
            self.layout.addWidget(self.table_righttop, 0, 65, 900, 45)
            self.layout.addWidget(self.list_backtestlog, 900, 65, 600, 45)
            self.layout.addWidget(self.table_middle, 1500, 65, 500, 45)
            self.setLayout(self.layout)
            '''
            #从策略配置文件读取参数设置self.mainstrategyname
            import configparser
            conf = configparser.ConfigParser()
            conf.read('./strategyfile/'+self.mainstrategyname+'.ini')
            sections = conf.sections()
            # 给字典增加key
            for i, j in enumerate(sections):
                options = conf.options(j)
                globalvar.dict_talibcondition[j] = []
                for m, n in enumerate(options):
                    globalvar.dict_talibcondition[j].append(conf.get(j, n))
            '''

        def callback_backtest_processbar(self, list):
            globalvar.DialogBackTestPoint.taskprogressBar.setProperty("value", list[0])
            globalvar.DialogBackTestPoint.taskprogressBar.setFormat(list[1])

        def UpdateProcessbar(self, diffsecond, instrumentname):
            # if 1:
            try:
                if False:
                    # if globalvar.DialogBackTestPoint.closestate == True:
                    globalvar.finishtasknum = globalvar.finishtasknum + 1
                    return
                # globalvar.finishtasknum = globalvar.finishtasknum + 1
                if globalvar.totaltasknum == 0:
                    return
                if globalvar.totaltasknum > 0:
                    rate = float(globalvar.finishtasknum) / float(globalvar.totaltasknum)
                    # diffsecond = (datetime.now() - self.starttime).seconds
                    h = int(diffsecond / 3600)
                    m = int((diffsecond - h * 3600) / 60)
                    s = diffsecond - h * 3600 - m * 60
                    if rate > 0:
                        leftsecond = int(float(diffsecond) * ((1.0 - rate) / rate))
                    else:
                        leftsecond = 0
                    h2 = int(leftsecond / 3600)
                    m2 = int((leftsecond - h2 * 3600) / 60)
                    s2 = leftsecond - h2 * 3600 - m2 * 60
                    usertime = "耗时%d:%02d:%02d 完成倒计时%d:%02d:%02d" % (h, m, s, h2, m2, s2)
                    thisvalue = float(100 * rate)
                    formattext = instrumentname + "(参数组)回测进度：%p% (" + str(globalvar.finishtasknum) + "\\" + str(
                        globalvar.totaltasknum) + ")" + usertime
                    self.callback_backtest_processbar([thisvalue, formattext])
            except Exception as e:
                print('OnFinish error:', e)

        def AddTradingRecordShow(self, filename):
            if os.path.isfile(filename):
                datalist = []
                dict_tradingday_buy = {}
                dict_tradingday_sell = {}
                self.table_middle.clear()
                self.table_middle.setRowCount(0)
                self.table_middle.setHorizontalHeaderLabels(['日期', '时间', '合约', '买卖', '开平', '成交价格', '委托手数'])
                with open(filename, 'r') as f:
                    for line in f:
                        datalist = line.strip('\n').split(',')
                        row_cnt = globalvar.DialogBackTestPoint.table_middle.rowCount()  # 返回当前行数（尾部）
                        globalvar.DialogBackTestPoint.table_middle.insertRow(row_cnt)  # 尾部插入一行新行表格
                        item = QTableWidgetItem(datalist[0])
                        globalvar.DialogBackTestPoint.table_middle.setItem(row_cnt, 0, item)
                        item = QTableWidgetItem(datalist[1])
                        globalvar.DialogBackTestPoint.table_middle.setItem(row_cnt, 1, item)
                        item = QTableWidgetItem(datalist[2])
                        globalvar.DialogBackTestPoint.table_middle.setItem(row_cnt, 2, item)
                        item = QTableWidgetItem(datalist[3])
                        globalvar.DialogBackTestPoint.table_middle.setItem(row_cnt, 3, item)
                        item = QTableWidgetItem(datalist[4])
                        globalvar.DialogBackTestPoint.table_middle.setItem(row_cnt, 4, item)
                        item = QTableWidgetItem(datalist[5])
                        globalvar.DialogBackTestPoint.table_middle.setItem(row_cnt, 5, item)
                        item = QTableWidgetItem(datalist[6])
                        globalvar.DialogBackTestPoint.table_middle.setItem(row_cnt, 6, item)
                        # list_tradingday_buy.append(datalist[0]+datalist[1])
                        # list_tradingday_sell.append(datalist[0] + datalist[1])
                        if len(datalist[1]) == 5:
                            datalist[1] = '0' + datalist[1]
                        if datalist[3] == '买':
                            dict_tradingday_buy[datalist[0] + datalist[1]] = True
                        else:
                            dict_tradingday_sell[datalist[0] + datalist[1]] = True
                return [dict_tradingday_buy, dict_tradingday_sell]
            else:
                return []

        def callback_backtest_result(self, arg):
            processid = -1
            try:
                processid = self.dict_processid[str(arg[2])]
            except Exception as e:
                self.dict_processid[str(arg[2])] = len(self.dict_processid)
                processid = self.dict_processid[str(arg[2])]
            self.UpdateProcessbar(int(arg[1]), str(arg[0][2]))
            globalvar.DialogBackTestPoint.table_right.insertRow(0)  # 插入一行新行表格
            item = QTableWidgetItem(str(arg[0][2]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 0, item)
            item = QTableWidgetItem(str(arg[0][0][0]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 1, item)
            item = QTableWidgetItem(str(arg[0][0][1]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 2, item)
            item = QTableWidgetItem(str(arg[0][0][2]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 3, item)
            item = QTableWidgetItem(str(arg[0][0][3]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 4, item)
            item = QTableWidgetItem(str(arg[0][0][4]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 5, item)
            item = QTableWidgetItem(str(arg[0][0][5]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 6, item)
            item = QTableWidgetItem(str(arg[0][1][0]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 7, item)
            item = QTableWidgetItem(str(int(arg[0][1][1])) + '%')
            globalvar.DialogBackTestPoint.table_right.setItem(0, 8, item)
            item = QTableWidgetItem(str(arg[0][1][2]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 9, item)
            item = QTableWidgetItem(str(arg[0][1][3]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 10, item)
            item = QTableWidgetItem(str(arg[0][1][4]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 11, item)
            item = QTableWidgetItem(str(arg[0][1][5]))
            globalvar.DialogBackTestPoint.table_right.setItem(0, 12, item)
            tempstr = str(arg[0][0][0]) + '_' + str(
                arg[0][0][1]) + '_' + str(
                arg[0][0][2]) + '_' + str(arg[0][0][3]) + '_' + str(arg[0][0][4]) + '_' + str(arg[0][0][5]) + '.txt'
            filename_tradingrecord = str(arg[0][2]) + '/tradingrecord/' + tempstr
            list_tradingday = self.AddTradingRecordShow(filename_tradingrecord)
            if self.selectbacktestcurl:
                filename_curl = str(arg[0][2]) + '/' + tempstr
                self.Function_UpdateEquityCurveByFileName(filename_curl, list_tradingday)

        def callback_backtest_loaddata(self, list):
            try:
                if list[0] == 1:
                    thisvalue = 100 * float(list[2])
                    globalvar.DialogBackTestPoint.taskdataBar.setProperty("value", thisvalue)
                    globalvar.DialogBackTestPoint.taskdataBar.setFormat(
                        str(list[3]) + " 加载到内存进度：%p% （已读取" + str(list[1]) + '行）')
                else:
                    thisvalue = 100 * float(list[2])
                    globalvar.DialogBackTestPoint.taskdataBar.setProperty("value", thisvalue)
                    globalvar.DialogBackTestPoint.taskdataBar.setFormat(
                        " 转换周期数据为" + str(list[3]) + "周期，已经转换 %p% （已读取" + str(list[1]) + '行）')
                '''
                globalvar.DialogBackTestPoint.progressbarlist[list[0]].setProperty("value", list[1])
                globalvar.DialogBackTestPoint.progressbarlist[list[0]].setFormat(list[2])
                if list[1] == 100:
                    globalvar.DialogBackTestPoint.progressbarlist[list[0]].setProperty("value", 0)
                    globalvar.DialogBackTestPoint.progressbarlist[list[0]].setFormat("回测进程等待")
                '''
            except Exception as e:
                print("callback_backtest_loaddata Error:" + repr(e))

        def callback_backtest_addresult(self, result):
            # row_cnt = self.table_righttop.rowCount()  # 返回当前行数（尾部
            self.table_righttop.insertRow(0)  # 插入一行新行表格
            filename = result[0][2].replace('backtestreport/', '')
            filename = filename.replace(globalvar.DialogBackTestPoint.mainstrategyname + '/', '')
            item = QTableWidgetItem(filename)
            self.table_righttop.setItem(0, 0, item)
            now = time.strftime("%Y-%m-%d %H:%M", time.localtime())
            item = QTableWidgetItem(now)
            self.table_righttop.setItem(0, 1, item)
            deleteButton2 = QPushButton("报告")
            deleteButton2.clicked.connect(self.Function_ReadInstrumentEquityCurveForButton)

            # item.connect(self.table_algorithmtrading, QtCore.SIGNAL("itemClicked(QTableWidgetItem*)"),
            #             self.function_item_clicked)

            self.table_righttop.setCellWidget(0, 2, deleteButton2)
            finishnum = self.table_righttop.rowCount()
            totalnum = self.table_leftbottom.rowCount()
            thisvalue = 100 * float(finishnum / totalnum)
            self.taskinstrumentIDBar.setProperty("value", thisvalue)
            self.taskinstrumentIDBar.setFormat(
                '完成 %p%（已完成回测合约数/总合约数 = ' + str(finishnum) + '/' + str(totalnum) + '）')

        def callback_backtest_adjustmentprice(self, list):
            try:
                thisvalue = 100 * float(list[1])
                globalvar.DialogBackTestPoint.taskdataBar.setProperty("value", thisvalue)
                globalvar.DialogBackTestPoint.taskdataBar.setFormat(
                    str(list[2]) + "，已复权 %p% （已读取" + str(list[0]) + '行）')
            except Exception as e:
                print("callback_backtest_adjustmentprice Error:" + repr(e))

        def GenerateBackTestFile(self):
            pass

        def OnSelectall(self):
            for i in range(self.table_leftbottom.rowCount()):
                self.table_leftbottom.item(i, 1).setCheckState(2)
                '''
                if self.table_leftbottom.item(i, 1).checkState():
                    temp = self.table_leftbottom.item(i, 1).text()
                    print('读取文件： ' + temp)
                    self.csvfile.append(self.table_leftbottom.item(i, 1).text())
                '''

        def OnSelectclearall(self):
            for i in range(self.table_leftbottom.rowCount()):
                self.table_leftbottom.item(i, 1).setCheckState(0)

        # def OnDownloadData(self):
        #    pass
        def OnOpenProcesswindow(self):
            print('OnOpenProcesswindow')

        def OnCloseProcesswindow(self):
            print('OnCloseProcesswindow')

        def OnOpenParAnalysisReport(self):
            window = module_backtestreport.LingBrowser()
            window.show()

            try:
                row_cnt = self.table_right.rowCount()  # 返回当前行数（尾部）
                if row_cnt == 0:
                    return
                print('tttttt: ' + self.table_right.item(0, 0).text())
                temp = self.table_right.item(0, 0).text().split('/')
                str = temp[0] + '/' + temp[1] + '/' + temp[2] + '/' + 'resultlist.csv'
                print('ttttttt: ' + str)
                print(self.mainstrategyname)
                # ui_demo = globalvar.ui.DialogParAnalysisReport('backtestreport/'+self.mainstrategyname, '')
                ui_demo = globalvar.ui.DialogParAnalysisReport(str, temp[3])
                screen = QDesktopWidget().screenGeometry()
                size = ui_demo.geometry()
                ui_demo.move((screen.width() - size.width()) / 2 - 180,
                             (screen.height() - size.height()) / 2 - 50)
                ui_demo.setWindowTitle('回测分析报告' + str)
                ui_demo.show()
                ui_demo.resize(1024, 600)
                # self.childwidget = self.childwidget(self)
                ui_demo.exec_()
            except Exception as e:
                print("OnOpenParAnalysisReport Error:" + repr(e))

        def OnStart_BackTest(self):
            if self.backteststate:
                # 停止回测
                self.backteststate = False
                self.closestate = True

                self.bt.OnStop('停止回测')
                globalvar.pool.terminate()
                # globalvar.pool.join()
            else:
                # 获取数据文件
                self.csvfile = []
                for i in range(self.table_leftbottom.rowCount()):
                    if self.table_leftbottom.item(i, 1).checkState():
                        temp = self.table_leftbottom.item(i, 1).text()
                        print('读取文件： ' + temp)
                        self.csvfile.append(self.table_leftbottom.item(i, 1).text())
                if len(self.csvfile) == 0:
                    messagebox = QMessageBox()
                    messagebox.setWindowTitle('提示')
                    messagebox.setText('请至少选中1个数据文件')
                    messagebox.setStandardButtons(QMessageBox.Yes)
                    buttonY = messagebox.button(QMessageBox.Yes)
                    buttonY.setText('确定')
                    reply = messagebox.exec_()
                    return
                # 开始回测
                self.backteststate = True
                processnum = globalvar.DialogBackTestPoint.comBox_process.currentIndex() + 1
                conditions0 = globalvar.DialogBackTestPoint.comBox_conditions0.currentText()
                conditions1 = globalvar.DialogBackTestPoint.comBox_conditions1.currentText()
                conditions2 = globalvar.DialogBackTestPoint.comBox_conditions2.currentText()
                adjustment = globalvar.DialogBackTestPoint.comBox_adjustment.currentText()
                # globalvar.BackTestThreadPoint.pardict.clear()
                self.table_middle.clear()
                self.table_middle.setRowCount(0)
                self.table_middle.setHorizontalHeaderLabels(['日期', '时间', '合约', '买卖', '开平', '成交价格', '委托手数'])
                self.progressbarlist.clear()
                self.bt = module_backtest.BackTestThread('module_bk')
                # self.bt.signal_backtest_processbar.connect(
                #    globalvar.DialogBackTestPoint.callback_backtest_processbar)  # 进程连接回传到GUI的事件
                self.bt.signal_backtest_result.connect(
                    globalvar.DialogBackTestPoint.callback_backtest_result)  # 进程连接回传到GUI的事件
                self.bt.signal_backtest_loaddata.connect(
                    globalvar.DialogBackTestPoint.callback_backtest_loaddata)  # 预处理数据
                self.bt.signal_backtest_addresult.connect(
                    globalvar.DialogBackTestPoint.callback_backtest_addresult)  # 增加某一个完成回测的合约记录
                self.bt.signal_backtest_adjustmentprice.connect(
                    globalvar.DialogBackTestPoint.callback_backtest_adjustmentprice)  # 复权
                self.bt.start()
                self.bt.OnStart(self.parnum, adjustment, conditions0, conditions1, conditions2)

        def OnStart_Next(self, fileid):
            self.callback_backtest_processbar([0, '数据载入进度%p%'])
            # 获取数据文件
            self.csvfile = []
            for i in range(self.table_leftbottom.rowCount()):
                if self.table_leftbottom.item(i, 1).checkState():
                    temp = self.table_leftbottom.item(i, 1).text()
                    print('读取文件： ' + temp)
                    self.csvfile.append(self.table_leftbottom.item(i, 1).text())
            if len(self.csvfile) == 0:
                messagebox = QMessageBox()
                messagebox.setWindowTitle('提示')
                messagebox.setText('请至少选中1个数据文件')
                messagebox.setStandardButtons(QMessageBox.Yes)
                buttonY = messagebox.button(QMessageBox.Yes)
                buttonY.setText('确定')
                reply = messagebox.exec_()
                return
            # 开始回测
            self.backteststate = True
            processnum = globalvar.DialogBackTestPoint.comBox_process.currentIndex() + 1
            conditions0 = globalvar.DialogBackTestPoint.comBox_conditions0.currentText()
            conditions1 = globalvar.DialogBackTestPoint.comBox_conditions1.currentText()
            conditions2 = globalvar.DialogBackTestPoint.comBox_conditions2.currentText()
            adjustment = globalvar.DialogBackTestPoint.comBox_adjustment.currentText()
            # globalvar.BackTestThreadPoint.pardict.clear()
            self.table_middle.clear()
            self.table_middle.setRowCount(0)
            self.table_middle.setHorizontalHeaderLabels(['日期', '时间', '合约', '买卖', '开平', '成交价格', '委托手数'])
            self.progressbarlist.clear()
            self.bt = module_backtest.BackTestThread('module_bk')
            # self.bt.signal_backtest_processbar.connect(
            #    globalvar.DialogBackTestPoint.callback_backtest_processbar)  # 进程连接回传到GUI的事件
            self.bt.signal_backtest_result.connect(
                globalvar.DialogBackTestPoint.callback_backtest_result)  # 进程连接回传到GUI的事件
            self.bt.signal_backtest_loaddata.connect(
                globalvar.DialogBackTestPoint.callback_backtest_loaddata)  # 预处理数据
            self.bt.signal_backtest_addresult.connect(
                globalvar.DialogBackTestPoint.callback_backtest_addresult)  # 增加某一个完成回测的合约记录
            self.bt.signal_backtest_adjustmentprice.connect(
                globalvar.DialogBackTestPoint.callback_backtest_adjustmentprice)  # 复权
            self.bt.start()
            self.bt.OnStartNext(self.parnum, adjustment, conditions0, conditions1, conditions2, fileid)
            #self.bt.OnStartNext(self.parnum, conditions0, conditions1, conditions2, fileid)



            '''
            # 获取数据文件
            self.csvfile = []
            for i in range(self.table_leftbottom.rowCount()):
                if self.table_leftbottom.item(i, 1).checkState():
                    temp = self.table_leftbottom.item(i, 1).text()
                    print('读取文件： ' + temp)
                    self.csvfile.append(self.table_leftbottom.item(i, 1).text())
            if len(self.csvfile) == 0:
                messagebox = QMessageBox()
                messagebox.setWindowTitle('提示')
                messagebox.setText('请至少选中1个数据文件')
                messagebox.setStandardButtons(QMessageBox.Yes)
                buttonY = messagebox.button(QMessageBox.Yes)
                buttonY.setText('确定')
                reply = messagebox.exec_()
                return
            '''
            '''
            # 开始回测
            self.backteststate = True
            processnum = globalvar.DialogBackTestPoint.comBox_process.currentIndex() + 1
            conditions0 = globalvar.DialogBackTestPoint.comBox_conditions0.currentText()
            conditions1 = globalvar.DialogBackTestPoint.comBox_conditions1.currentText()
            conditions2 = globalvar.DialogBackTestPoint.comBox_conditions2.currentText()
            # globalvar.BackTestThreadPoint.pardict.clear()
            self.table_middle.clear()
            self.table_middle.setRowCount(0)
            self.table_middle.setHorizontalHeaderLabels(['进程任务进度条'])
            self.progressbarlist.clear()
            for k in range(processnum):
                row_cnt = self.table_middle.rowCount()  # 返回当前行数（尾部）
                self.table_middle.insertRow(row_cnt)  # 尾部插入一行新行表格
                column_cnt = self.table_middle.columnCount()  # 返回当前列数
                item = QTableWidgetItem("")
                self.table_middle.setItem(row_cnt, 0, item)
                progressBar = QtWidgets.QProgressBar()
                progressBar.setProperty("progressBar", 0)
                progressBar.setObjectName("progressBar")
                self.progressbarlist.append(progressBar)
                self.table_middle.setCellWidget(row_cnt, 0, progressBar)

            self.bt = module_backtest.BackTestThread('module_bk')
            # self.bt.signal_backtest_processbar.connect(
            #    globalvar.DialogBackTestPoint.callback_backtest_processbar)  # 进程连接回传到GUI的事件
            self.bt.signal_backtest_result.connect(
                globalvar.DialogBackTestPoint.callback_backtest_result)  # 进程连接回传到GUI的事件
            self.bt.signal_backtest_loaddata.connect(
                globalvar.DialogBackTestPoint.callback_backtest_loaddata)  # 预处理数据
            self.bt.signal_backtest_addresult.connect(
                globalvar.DialogBackTestPoint.callback_backtest_addresult)  # 增加某一个完成回测的合约记录
            self.bt.start()
            self.bt.OnStartNext(self.parnum, conditions0, conditions1, conditions2, fileid)
            '''

    # 为策略选中交易合约组窗口
    class DialogSetInstrumentID(QtWidgets.QDialog):
        def __init__(self, strategyname):
            super().__init__()
            # print('kkkk: '+os.path.splitext(strategyname)[-1])  #.py
            # print('LLL: '+os.path.splitext(strategyname)[0])  #strategyfile\EMA策略
            # print('MMM: '+os.path.splitext(strategyname)[1])  #.py
            self.strategyname = os.path.splitext(strategyname)[0] + '.csv'
            self.InitUI()

        def closeEvent(self, event):
            globalvar.DialogSetInstrumentState = False
            '''
            try:
                if self.dlg_talibindicatrixsetting:
                    self.dlg_talibindicatrixsetting.close()
            except Exception as e:
                print("DialogTalib closeEvent Error:" + repr(e))
            '''

        '''
        def sync_table_double_clicked(self, index):
            column = index.column()
            row = index.row()
            self.strategyname = self.tableWidget.item(row, column).text()
            print("table1: " + self.name)
        '''

        # 扫描合约组设置
        dict_instrumentgroup = {}
        deleteButtonlist = []

        # 从文件读取合约组信息
        def ReadInstrumentIDGroupInfo(self, filename):
            grouplist = []
            with open(filename, 'r') as f:
                for line in f:
                    grouplist = line.strip('\n').split(',')
            return len(grouplist)

        def Function_ScanInstrumentIDGroupDlg(self):
            path = "instrumentgroup"
            ls = os.listdir(path)
            buttonid = 0
            for i in ls:
                c_path = os.path.join(path, i)
                if os.path.isdir(c_path):
                    print(c_path)
                    globalvar.ui.ClearPath(c_path)
                else:
                    file = os.path.splitext(c_path)
                    filename, type = file
                    if type == ".csv":
                        '''
                        if c_path in dict_instrumentgroup:
                            print('AAA: '+dict_instrumentgroup[c_path])
                            print('BBB: '+ globalvar.ui.fileTime(c_path))

                            if dict_instrumentgroup[c_path] != globalvar.ui.fileTime(c_path):
                                print("修改了")
                        '''
                        if True:
                            # else:
                            try:
                                filenameini = c_path
                                filenameini = filenameini.replace('py', 'ini')
                                '''
                                #  实例化configParser对象
                                config = configparser.ConfigParser()
                                # -read读取ini文件
                                config.read(filenameini, encoding='utf-8')
                                if config.getint('setting', 'run') == 1:
                                    dict_instrumentgrouprun[c_path] = 1
                                else:
                                    dict_instrumentgrouprun[c_path] = 0
                                '''
                                self.dict_instrumentgroup[c_path] = globalvar.ui.fileTime(c_path)
                                # print("find Strategy file:", c_path,globalvar.ui.fileTime(c_path))
                                row_cnt = self.tableWidget.rowCount()  # 返回当前行数（尾部）
                                # print("列数：",row_cnt)
                                self.tableWidget.insertRow(row_cnt)  # 尾部插入一行新行表格
                                column_cnt = self.tableWidget.columnCount()  # 返回当前列数
                                # for column in range(column_cnt):
                                item = QTableWidgetItem(str(row_cnt + 1))
                                self.tableWidget.setItem(row_cnt, 0, item)
                                item = QTableWidgetItem(str(c_path))
                                self.tableWidget.setItem(row_cnt, 1, item)
                                item = QTableWidgetItem(str(self.ReadInstrumentIDGroupInfo(str(c_path))))
                                self.tableWidget.setItem(row_cnt, 2, item)
                                item = QTableWidgetItem('备注')
                                self.tableWidget.setItem(row_cnt, 3, item)

                                item = QTableWidgetItem('选择(等待升级，暂时无法修改，全部订阅合约生效)')
                                try:
                                    if True:
                                        # if self.dict_EnableInstrumentID[globalvar.ui.table_instrument.item(i, 2).text()]:
                                        item.setCheckState(QtCore.Qt.Checked)
                                    else:
                                        item.setCheckState(QtCore.Qt.Unchecked)
                                except Exception as e:
                                    item.setCheckState(QtCore.Qt.Unchecked)
                                self.tableWidget.setItem(row_cnt, 4, item)

                                '''
                                self.deleteButton = QPushButton("编辑合约组" + str(i))
                                self.deleteButtonlist.append(self.deleteButton)
                                #暂时屏蔽 deleteButton.clicked.connect(self.Function_Clicked_EditInstrumentID)
                                buttonid = buttonid + 1
                                self.tableWidget.setCellWidget(row_cnt, 4, self.deleteButton)
                                '''


                            except Exception as e:
                                print("Function_ScanInstrumentIDGroupDlg Error:" + repr(e))

        def InitUI(self):
            self.setWindowIcon(QIcon(r'setinstrument.ico'))  # 设置窗口图标
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            self.layout = QHBoxLayout()
            self.btn_left = QPushButton('选中全部主力合约', self)
            self.btn_right = QPushButton('清空合约', self)

            self.tableWidget = QtWidgets.QTableWidget()
            self.tableWidget.setObjectName("tableWidget")
            self.tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直表头
            self.tableWidget.horizontalHeader().setVisible(True)  # 隐藏水平表头
            self.tableWidget.setColumnCount(5)
            self.tableWidget.setRowCount(0)
            self.tableWidget.setEditTriggers(QTableView.NoEditTriggers)
            self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.tableWidget.setHorizontalHeaderLabels(
                ['ID', '合约组名称', '选入合约数量', '备注', '操作'])  # 设置表头文字
            # self.tableWidget.doubleClicked.connect(self.Function_doubleClicked_strategy)
            self.tableWidget.setColumnWidth(0, 80)
            self.tableWidget.setColumnWidth(1, 255)
            self.tableWidget.setColumnWidth(2, 150)
            self.tableWidget.setColumnWidth(3, 150)
            self.tableWidget.setColumnWidth(4, 250)
            self.tableWidget.setRowHeight(0, 30)
            # self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自动拉伸，充满界面
            self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            # self.tableWidget.setSortingEnabled(True)  # 设置表头可以自动排序
            self.tab_tableWidget = QtWidgets.QWidget()
            self.tab_tableWidget.setObjectName("tab_tableWidget")

            self.layout = QtWidgets.QGridLayout(self.tab_tableWidget)
            self.layout.setContentsMargins(0, 0, 0, 0)
            self.layout.setObjectName("gridLayout_strategy")
            # self.tableWidget.setCellWidget(0, 8, Trade_BacktestingBtn)
            self.layout.addWidget(self.tableWidget, 0, 0, 1, 1)
            # self.layout.addWidget(self.list_instrumentidgroupselect, 0, 4, 1, 3)
            # self.layout.addWidget(self.btn_left, 2, 0, 4, 4)
            # self.layout.addWidget(self.btn_right, 2, 4, 4, 3)
            # self.tableWidget.doubleClicked.connect(self.sync_table_double_clicked)
            # 恢复 self.setWindowTitle(
            #    self.strategyname + '【' + module_talib.dict_talibparameter[self.strategyname][0][1] + '】')
            '''
            恢复
            parnum = int(module_talib.dict_talibparameter[self.strategyname][0][0])
            parameter = ['', '', '', '', '', '']
            DEFAULTVALUE = -1
            id = 0
            for k in range(parnum):
                if module_talib.dict_talibparameter[self.strategyname][2][k] != DEFAULTVALUE:
                    parameter[id] = module_talib.dict_talibparameter[self.strategyname][1][k]
                    id = id + 1

            self.tableWidget.setHorizontalHeaderLabels(
                ['状态', '备注', '参数1', '参数2', '参数3', '参数4', '参数5'])
            '''

            self.setLayout(self.layout)
            # 参数个数
            labelpar = []

            self.Function_ScanInstrumentIDGroupDlg()

            try:
                for i in range(len(globalvar.dict_talibcondition[self.strategyname])):
                    # print('lid: ' + str(globalvar.dict_talibcondition[self.strategyname][i]))
                    item = QTableWidgetItem(' 启用该条件')
                    if globalvar.dict_talibcondition[self.strategyname][i][1] == 1:
                        item.setCheckState(QtCore.Qt.Checked)
                    else:
                        item.setCheckState(QtCore.Qt.Checked)
                    # item.connect(self.table_algorithmtrading, QtCore.SIGNAL("itemClicked(QTableWidgetItem*)"), self.function_item_clicked)
                    self.tableWidget.setItem(i, 0, item)
                    item = QTableWidgetItem(globalvar.dict_talibcondition[self.strategyname][i][2])
                    self.tableWidget.setItem(i, 1, item)
                    item = QTableWidgetItem(globalvar.dict_talibcondition[self.strategyname][i][3])
                    self.tableWidget.setItem(i, 2, item)
                    item = QTableWidgetItem(globalvar.dict_talibcondition[self.strategyname][i][4])
                    self.tableWidget.setItem(i, 3, item)
            except Exception as e:
                print("dict_talibcondition Error:" + repr(e))

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                            '选择期货公司:')
            if ok:
                self.le.setText(str(text))

    # 编辑合约组里的合约窗口
    class DialogEditInstrumentID(QtWidgets.QDialog):
        def __init__(self, filename):
            super().__init__()
            self.filename = filename
            self.InitUI()

        def closeEvent(self, event):
            globalvar.DialogSetInstrumentState = False
            '''
            try:
                if self.dlg_talibindicatrixsetting:
                    self.dlg_talibindicatrixsetting.close()
            except Exception as e:
                print("DialogTalib closeEvent Error:" + repr(e))
            '''

        '''
        def sync_table_double_clicked(self, index):
            column = index.column()
            row = index.row()
            self.strategyname = self.tableWidget.item(row, column).text()
            print("table1: " + self.name)
        '''

        readfinish = False
        # 保存已经生效的合约
        dict_EnableInstrumentID = {}

        # 读取股票图表访问历史列表
        def ReadInstrumentIDGroup(self):
            returnvalue = False
            with open(self.filename, 'r') as f:
                for line in f:
                    enablelist = line.strip('\n').split(',')
                    if len(enablelist) > 0:
                        for j in range(len(enablelist)):
                            _translate = QtCore.QCoreApplication.translate
                            item = QtWidgets.QListWidgetItem()
                            self.list_instrumentidgroupselect.addItem(item)
                            item = self.list_instrumentidgroupselect.item(
                                self.list_instrumentidgroupselect.count() - 1)
                            item.setText(_translate("MainWindow", enablelist[j]))
                            self.dict_EnableInstrumentID[enablelist[j]] = True
                        returnvalue = True
                    else:
                        returnvalue = False
                self.readfinish = True
            return returnvalue

        # 选入合约（更新显示，更新文件，更新内存变量）
        def AddAndUpdateInstrumentIDGroupFile(self, InstrumentID):
            _translate = QtCore.QCoreApplication.translate
            item = QtWidgets.QListWidgetItem()
            self.list_instrumentidgroupselect.addItem(item)
            item = self.list_instrumentidgroupselect.item(self.list_instrumentidgroupselect.count() - 1)
            item.setText(_translate("MainWindow", InstrumentID))
            self.dict_EnableInstrumentID[InstrumentID] = True
            with open(self.filename, 'r') as f:
                for line in f:
                    line = line + ',' + InstrumentID
                    with open(self.filename, "w") as f:
                        f.write(line)
                    return

        # 删除合约（更新显示，更新文件，更新内存变量）
        def RemoveAndUpdateInstrumentIDGroupFile(self, InstrumentID):
            '''
            tconut=self.list_instrumentidgroupselect.count()
            if tconut>0:
                for index in range(tconut):
                    item = self.list_instrumentidgroupselect.item(index)
                    if item.text() == InstrumentID:
                        #self.list_instrumentidgroupselect.tackItem(item)
                        self.list_instrumentidgroupselect.removeItemWidget(item)
                        del item
                        break
            '''
            # self.dict_EnableInstrumentID[InstrumentID] = False
            with open(self.filename, 'r') as f:
                for line in f:
                    line = line.replace(InstrumentID, '')
                    line = line.replace(',,', ',')
                    print(line)
                    if line[-1] == ',':
                        line = line[:-1]
                    print(line)
                    if line[0] == ',':
                        line = line[1:]
                    print(line)
                    with open(self.filename, "w") as f:
                        f.write(line)
                    continue
            self.dict_EnableInstrumentID.clear()
            self.list_instrumentidgroupselect.clear()
            self.ReadInstrumentIDGroup()

        # checkbox改变事件，选入合约或删除合约
        def OnCellChanged(self, row, column):
            LastStateRole = QtCore.Qt.UserRole
            if self.readfinish:
                if column != 3:
                    return
                item = self.tableWidget.item(row, column)
                lastState = item.data(LastStateRole)
                currentState = item.checkState()
                if currentState != lastState:
                    # print('changed(group)')
                    AddInstrumentID = globalvar.ui.table_instrument.item(row, 2).text()
                    if currentState == QtCore.Qt.Checked:
                        # print('checked(group): '+AddInstrumentID)
                        self.AddAndUpdateInstrumentIDGroupFile(AddInstrumentID)
                    else:
                        self.RemoveAndUpdateInstrumentIDGroupFile(AddInstrumentID)
                        # print("unchecked(group)")
                    item.setData(LastStateRole, currentState)

        def InitUI(self):
            self.setWindowIcon(QIcon(r'setinstrument.ico'))  # 设置窗口图标
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            self.tableWidget = QTableWidget()
            self.layout = QHBoxLayout()
            self.btn_left = QPushButton('', self)
            self.btn_right = QPushButton('', self)
            row_cnt = globalvar.ui.table_instrument.rowCount()  # 返回当前行数（尾部）
            self.tableWidget.setObjectName("setinstrument")
            self.tableWidget.verticalHeader().setVisible(True)  # 隐藏垂直表头
            self.tableWidget.horizontalHeader().setVisible(True)  # 隐藏水平表头
            self.tableWidget.setEditTriggers(QTableView.NoEditTriggers)
            self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.tableWidget.setColumnCount(4)
            self.tableWidget.setRowCount(row_cnt)
            self.tableWidget.setHorizontalHeaderLabels(
                ['合约', '合约代码', '交易所', '加入'])  # 设置表头文字
            self.tableWidget.setSortingEnabled(True)  # 设置表头可以自动排序
            self.tab_tableWidget = QtWidgets.QWidget()
            self.tab_tableWidget.setObjectName("tab_tableWidget")
            self.list_instrumentidgroupselect = QtWidgets.QListWidget(self.tab_tableWidget)
            self.list_instrumentidgroupselect.setObjectName("list_instrumentidgroupselect")
            _translate = QtCore.QCoreApplication.translate
            __sortingEnabled = self.list_instrumentidgroupselect.isSortingEnabled()
            self.list_instrumentidgroupselect.setSortingEnabled(False)
            self.list_instrumentidgroupselect.setSortingEnabled(__sortingEnabled)
            self.layout = QtWidgets.QGridLayout(self.tab_tableWidget)
            self.layout.setContentsMargins(0, 0, 0, 0)
            self.layout.setObjectName("gridLayout_strategy")
            # self.tableWidget.setCellWidget(0, 8, Trade_BacktestingBtn)
            self.layout.addWidget(self.tableWidget, 0, 0, 1, 4)
            self.layout.addWidget(self.list_instrumentidgroupselect, 0, 4, 1, 3)
            self.layout.addWidget(self.btn_left, 2, 0, 4, 4)
            self.layout.addWidget(self.btn_right, 2, 4, 4, 3)
            # self.list_instrumentidgroupselect.clear()
            # self.tableWidget.doubleClicked.connect(self.sync_table_double_clicked)
            # 读取已经设置的合约列表，在对话框右边视图显示
            self.ReadInstrumentIDGroup()
            # indexes = globalvar.ui.table_instrumentcx.selectedIndexes()  # 获取表格对象中被选中的数据索引列表
            for i in range(row_cnt):
                for j in range(4 - 1):
                    strs = globalvar.ui.table_instrument.item(i, j + 1).text()
                    item = QTableWidgetItem(strs)
                    self.tableWidget.setItem(i, j, item)
                item = QTableWidgetItem('选择')
                try:
                    if self.dict_EnableInstrumentID[globalvar.ui.table_instrument.item(i, 2).text()]:
                        item.setCheckState(QtCore.Qt.Checked)
                    else:
                        item.setCheckState(QtCore.Qt.Unchecked)
                except Exception as e:
                    item.setCheckState(QtCore.Qt.Unchecked)
                self.tableWidget.setItem(i, 3, item)
            self.tableWidget.cellChanged.connect(self.OnCellChanged)

            '''
            恢复
            parnum = int(module_talib.dict_talibparameter[self.strategyname][0][0])
            parameter = ['', '', '', '', '', '']
            DEFAULTVALUE = -1
            id = 0
            for k in range(parnum):
                if module_talib.dict_talibparameter[self.strategyname][2][k] != DEFAULTVALUE:
                    parameter[id] = module_talib.dict_talibparameter[self.strategyname][1][k]
                    id = id + 1

            self.tableWidget.setHorizontalHeaderLabels(
                ['状态', '备注', '参数1', '参数2', '参数3', '参数4', '参数5'])
            '''

            '''
            try:
                print("table111: " + self.strategyname)
                print("table222")
                print(str(module_talib.dict_talibparameter))
                print('查询1'+str(module_talib.dict_talibparameter[self.strategyname]))
                # 输出：查询1[[0], ['cx1', 'cx2', 'cx3'], [3, 5, 10], [4, 6, 18]]
                print('查询2'+str(module_talib.dict_talibparameter[self.strategyname][1]))
                print('查询3 启动状态, ' + str(module_talib.dict_talibparameter[self.strategyname][0][0]))
                print('查询4 参数组个数 ' +          str(module_talib.dict_talibparameter[self.strategyname][0][1]))
                # module_talib.dict_talibparameter[self.strategyname][0][0]    [#启动状态 ]
                # module_talib.dict_talibparameter[self.strategyname][0][1]    [#参数组个数 ]
                # module_talib.dict_talibparameter[self.strategyname][1][1]    [#参数1, #参数2,..... #参数n]
                # module_talib.dict_talibparameter[self.strategyname][2]    [参数组1]
                # module_talib.dict_talibparameter[self.strategyname][3]    [参数组2]
                # module_talib.dict_talibparameter[self.strategyname][4]    [参数组3]
            except Exception as e:
                print("initUI Error:" + repr(e))
            '''
            self.setLayout(self.layout)
            # 参数个数
            labelpar = []

            def function_item_clicked(self, QTableWidgetItem):
                check_state = QTableWidgetItem.checkState()
                row = QTableWidgetItem.row()
                if check_state == QtCore.Qt.Checked:
                    if row not in self.delete_row:
                        self.delete_row.append(row)
                elif check_state == QtCore.Qt.Unchecked:
                    if row in self.delete_row:
                        self.delete_row.remove(row)

            try:
                for i in range(len(globalvar.dict_talibcondition[self.strategyname])):
                    # print('lid: ' + str(globalvar.dict_talibcondition[self.strategyname][i]))
                    item = QTableWidgetItem(' 启用该条件')
                    if globalvar.dict_talibcondition[self.strategyname][i][1] == 1:
                        item.setCheckState(QtCore.Qt.Checked)
                    else:
                        item.setCheckState(QtCore.Qt.Checked)
                    # item.connect(self.table_algorithmtrading, QtCore.SIGNAL("itemClicked(QTableWidgetItem*)"), self.function_item_clicked)
                    self.tableWidget.setItem(i, 0, item)
                    item = QTableWidgetItem(globalvar.dict_talibcondition[self.strategyname][i][2])
                    self.tableWidget.setItem(i, 1, item)
                    item = QTableWidgetItem(globalvar.dict_talibcondition[self.strategyname][i][3])
                    self.tableWidget.setItem(i, 2, item)
                    item = QTableWidgetItem(globalvar.dict_talibcondition[self.strategyname][i][4])
                    self.tableWidget.setItem(i, 3, item)
            except Exception as e:
                print("dict_talibcondition Error:" + repr(e))

            try:
                for i in range(len(module_talib.dict_talibparameter[self.strategyname][3][0])):
                    tempparlabel2 = QLabel(self)
                    EditPar = QLineEdit(self)
                    EditPar2 = QLineEdit(self)
                    tempparlabel2.setText(str(module_talib.dict_talibparameter[self.strategyname][3][0][0]))
                    tempparlabel2.move(60, 230 + parnum * 40)
                    EditPar.setText('>' + str(module_talib.dict_talibparameter[self.strategyname][3][0][1]))
                    EditPar.move(200, 230 + parnum * 40)
                    EditPar.resize(120, 30)
                    EditPar2.setText('趋势条件')
                    EditPar2.move(400, 230 + parnum * 40)
                    EditPar2.resize(120, 30)
            except Exception as e:
                print("talib.csv格式错误 Error:" + repr(e))
                return

            '''
            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(330, 265)
            self.btn_authcode.resize(130, 30)
            #self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)
            '''

            self.btn_ok = QPushButton('添加指标条件', self)
            self.btn_ok.move(300, 480)
            self.btn_ok.resize(300, 50)
            Edit2 = QLineEdit(self)
            Edit2.setText('（该指标条件可用于组合成策略）')
            Edit2.move(360, 550)
            Edit2.resize(180, 30)

            self.setGeometry(500, 600, 420, 450)
            self.show()
            try:
                global config
                config = configparser.ConfigParser()
                # -read读取ini文件
                config.read('vnctptd.ini', encoding='utf-8')
                brokeid = config.get('setting', 'brokeid')
                investor = config.get('setting', 'investor')
                password = config.get('setting', 'password')
                appid = config.get('setting', 'appid')
                userproductinfo = config.get('setting', 'userproductinfo')
                authcode = config.get('setting', 'authcode')
                address1 = config.get('setting', 'address1')
                address2 = config.get('setting', 'address2')
                address3 = config.get('setting', 'address3')
                print('read %s %s %s' % (investor, password, appid))
                self.Edit_brokerid.setText(brokeid)
                self.Edit_investor.setText(investor)
                self.Edit_password.setText(password)
                self.Edit_APPID.setText(appid)
                self.Edit_authcode.setText(authcode)
                self.Edit_auserproductinfo.setText(userproductinfo)
                self.Edit_addr1.setText(address1)
                self.Edit_addr2.setText(address2)
                self.Edit_addr3.setText(address3)
            except Exception as e:
                print("initUI Error:" + repr(e))

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                            '选择期货公司:')
            if ok:
                self.le.setText(str(text))

    # 打开量化回测结果窗口
    class DialogFinishResult(QtWidgets.QDialog):
        def __init__(self, titlepath, indexfilename):
            super().__init__()
            self.path = titlepath
            # self.strategyname = indexfilename
            # self.mainstrategyname = os.path.splitext(indexfilename)[0]
            # self.mainstrategyname = self.mainstrategyname.replace('strategyfile\\', "")
            # self.csvstrategyname = os.path.splitext(indexfilename)[0] + '.csv'
            self.InitUI(indexfilename)

        def Function_UpdateEquityCurve(self):
            try:
                # 读取资金曲线数据文件，并更新到pyqtgraph
                filename = self.path + self.table_right.selectedItems()[0].text() + '_' + \
                           self.table_right.selectedItems()[
                               1].text() + '_' + self.table_right.selectedItems()[2].text() + '_' + \
                           self.table_right.selectedItems()[
                               3].text() + '_' + self.table_right.selectedItems()[4].text() + '_' + \
                           self.table_right.selectedItems()[5].text() + '.txt'
                data_backtest = []
                '''
                data_index_buy =[]
                data_value_buy =[]
                data_index_sell = []
                data_value_sell = []
                print('filename:' + filename)
                '''
                # index=0
                with open(filename, 'r') as f:
                    for line in f:
                        linelist = line.strip('\n').split(',')
                        data_backtest.append(float(linelist[2]))
                        '''index+=1
                        if index%10==0:
                            data_index_buy.append(index)
                            data_value_buy.append(float(linelist[2]))
                        if index%20==0:
                            data_index_sell.append(index)
                            data_value_sell.append(float(linelist[2]))
                        '''
                # self.curve_realtime.setData(np.hstack(data_backtest))
                # self.plt_realtime.plot(x=data_index_buy,  y=data_value_buy, pen='r', name='买入', symbolBrush=(255, 0, 0), )
                # self.plt_realtime.plot(x=data_index_sell, y=data_value_sell, pen='g', name='卖出', symbolBrush=(0, 255, 0))

                # self.curve_buy = self.plt_realtime.plot(x=[], y=[], pen='r', name='买入', symbolBrush=(255, 0, 0), )
                # self.curve_sell = self.plt_realtime.plot(x=[], y=[], pen='g', name='卖出', symbolBrush=(0, 255, 0))
                # self.curve_buy.setData(np.hstack(data_index_buy),np.hstack(data_value_buy))
                # self.curve_sell.setData(np.hstack(data_index_sell),np.hstack(data_value_sell))
                '''
                self.plt_realtime.plot(x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                                       y=[4000, 4010, 4020, 4030, 4040, 4050, 4060, 4070, 4080, 4090], pen='r',
                                       name='开盘指数', symbolBrush=(255, 0, 0), )
                self.plt_realtime.plot(x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                                       y=[3500, 3510, 3520, 3530, 3540, 3540, 3540, 3570, 3540, 3590], pen='g',
                                       name='收盘指数', symbolBrush=(0, 255, 0))
                '''
                # self.plt_realtime.plot(x=[1,2,3,4,5,6,7,8,9,10], y=[4000,4010,4020,4030,4040,4050,4060,4070,4080,4090], pen='r', name='开盘指数', symbolBrush=(255, 0, 0), )
                # self.plt_realtime.plot(x=[1,2,3,4,5,6,7,8,9,10], y=[3500,3510,3520,3530,3540,3540,3540,3570,3540,3590], pen='g', name='收盘指数', symbolBrush=(0, 255, 0))
            except Exception as e:
                pass

        def Function_UpdateEquityCurveByFileName(self, filename):
            # 读取资金曲线数据文件，并更新到pyqtgraph
            try:
                data_backtest = []
                with open(filename, 'r') as f:
                    for line in f:
                        linelist = line.strip('\n').split(',')
                        data_backtest.append(float(linelist[2]))
                self.curve_realtime.setData(np.hstack(data_backtest))
            except Exception as e:
                pass

        def InitUI(self, indexfilename):
            self.setWindowIcon(QIcon(r'setinstrument.ico'))  # 设置窗口图标
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            self.setWindowFlags(QtCore.Qt.Widget)
            self.layout = QHBoxLayout()
            self.table_right = QtWidgets.QTableWidget()
            self.table_right.setObjectName("table_right")
            self.table_right.setColumnCount(12)
            self.table_right.setRowCount(0)
            self.table_right.setEditTriggers(QTableView.NoEditTriggers)
            self.table_right.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.table_right.setHorizontalHeaderLabels(
                ['参数1', '参数2', '参数3', '参数4', '参数5', '参数6', '权益', '收益率', '胜率', '盈亏比', '交易次数', '夏普率'])
            self.table_right.setRowHeight(0, 28)
            self.table_right.setColumnWidth(0, 40)
            self.table_right.setColumnWidth(1, 40)
            self.table_right.setColumnWidth(2, 40)
            self.table_right.setColumnWidth(3, 40)
            self.table_right.setColumnWidth(4, 40)
            self.table_right.setColumnWidth(5, 40)
            self.table_right.setColumnWidth(6, 40)
            self.table_right.setColumnWidth(7, 90)
            self.table_right.setColumnWidth(8, 85)
            self.table_right.setColumnWidth(9, 85)
            self.table_right.setColumnWidth(10, 85)
            self.table_right.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            self.table_right.clicked.connect(self.Function_UpdateEquityCurve)
            self.table_right.doubleClicked.connect(self.Function_UpdateEquityCurve)
            self.table_right.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            # 资金曲线图
            self.wincurl = pg.GraphicsLayoutWidget(show=True, size=(400, 250))
            self.wincurl.setWindowTitle('回测资金曲线')
            self.plt_realtime = self.wincurl.addPlot(title="回测资金曲线")
            self.curve_realtime = self.plt_realtime.plot(pen='y')
            self.plt_realtime.setMouseEnabled(x=False, y=False)  # 禁用轴操作
            self.wincurl.showMaximized()
            # 资金曲线图
            self.tab_tableWidget = QtWidgets.QWidget()
            self.tab_tableWidget.setObjectName("tab_tableWidget")
            self.list_backtestlog = QtWidgets.QListWidget(self.tab_tableWidget)
            self.list_backtestlog.setObjectName("list_backtestlog")
            _translate = QtCore.QCoreApplication.translate
            __sortingEnabled = self.list_backtestlog.isSortingEnabled()
            self.list_backtestlog.setSortingEnabled(False)
            self.list_backtestlog.setSortingEnabled(__sortingEnabled)
            self.layout = QtWidgets.QGridLayout(self.tab_tableWidget)
            self.layout.setContentsMargins(0, 0, 0, 0)
            self.layout.setObjectName("layout")
            self.layout.addWidget(self.table_right, 0, 0, 200, 50)
            self.layout.addWidget(self.wincurl, 200, 0, 100, 50)
            self.setLayout(self.layout)
            lindid = 0
            with open(indexfilename, 'r') as f:
                for line in f:
                    strlist = line.split(",")
                    self.table_right.insertRow(lindid)
                    # item = QTableWidgetItem('参数' + str(i + 1))
                    item = QTableWidgetItem(strlist[0])
                    # item.setFlags(QtCore.Qt.ItemIsEnabled)
                    self.table_right.setItem(lindid, 0, item)
                    item = QTableWidgetItem(strlist[1])
                    self.table_right.setItem(lindid, 1, item)
                    item = QTableWidgetItem(strlist[2])
                    self.table_right.setItem(lindid, 2, item)
                    item = QTableWidgetItem(strlist[3])
                    self.table_right.setItem(lindid, 3, item)
                    item = QTableWidgetItem(strlist[4])
                    self.table_right.setItem(lindid, 4, item)
                    item = QTableWidgetItem(strlist[5])
                    self.table_right.setItem(lindid, 5, item)
                    item = QTableWidgetItem(strlist[6])
                    self.table_right.setItem(lindid, 6, item)
                    item = QTableWidgetItem(strlist[7])
                    self.table_right.setItem(lindid, 7, item)
                    item = QTableWidgetItem(strlist[8])
                    self.table_right.setItem(lindid, 8, item)
                    item = QTableWidgetItem(strlist[9])
                    self.table_right.setItem(lindid, 9, item)
                    item = QTableWidgetItem(strlist[10])
                    self.table_right.setItem(lindid, 10, item)
                    item = QTableWidgetItem(strlist[11])
                    self.table_right.setItem(lindid, 11, item)
                    lindid += 1

    # 参数组分析报告
    from PyQt5.QtWebEngineWidgets import QWebEngineView
    class DialogParAnalysisReport(QtWidgets.QDialog):
        def __init__(self, indexfilename, csvfile):
            super().__init__()
            self.InitUI(indexfilename)

        def Function_OpenAnalysisReport(self):
            self.webview = WebEngineView()
            self.webview.load(QUrl("https://www.baidu.com"))
            self.setCentralWidget(self.webview)

            with open("reporttemplate/template.html", "r") as f:
                for line in f.readlines():
                    line = line.strip('\n')
                    strlist = line.split(",")
            pass

        def InitUI(self, indexfilename):
            self.setWindowIcon(QIcon(r'setinstrument.ico'))  # 设置窗口图标
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            self.setWindowFlags(QtCore.Qt.Widget)
            self.layout = QHBoxLayout()
            self.table_right = QtWidgets.QTableWidget()
            self.table_right.setObjectName("table_right")
            self.table_right.setColumnCount(8)
            self.table_right.setRowCount(0)
            self.table_right.setEditTriggers(QTableView.NoEditTriggers)
            self.table_right.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.table_right.setHorizontalHeaderLabels(
                ['ID', '合约', '盈利参数组个数', '亏损参数组个数', '盈利参数组占比', '盈利参数组平均盈利', '亏损参数组平均亏损', '操作'])
            self.table_right.setRowHeight(0, 28)
            self.table_right.setColumnWidth(0, 40)
            self.table_right.setColumnWidth(1, 40)
            self.table_right.setColumnWidth(2, 40)
            self.table_right.setColumnWidth(3, 40)
            self.table_right.setColumnWidth(4, 40)
            self.table_right.setColumnWidth(5, 40)
            self.table_right.setColumnWidth(6, 40)
            self.table_right.setSelectionMode(QAbstractItemView.NoSelection)  # 设置只能选中一行
            # self.table_right.clicked.connect(self.Function_UpdateEquityCurve)
            # self.table_right.doubleClicked.connect(self.Function_UpdateEquityCurve)
            self.table_right.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            self.tab_tableWidget = QtWidgets.QWidget()
            self.tab_tableWidget.setObjectName("tab_tableWidget")
            self.list_backtestlog = QtWidgets.QListWidget(self.tab_tableWidget)
            self.list_backtestlog.setObjectName("list_backtestlog")
            _translate = QtCore.QCoreApplication.translate
            __sortingEnabled = self.list_backtestlog.isSortingEnabled()
            self.list_backtestlog.setSortingEnabled(False)
            self.list_backtestlog.setSortingEnabled(__sortingEnabled)
            self.layout = QtWidgets.QGridLayout(self.tab_tableWidget)
            self.layout.setContentsMargins(0, 0, 0, 0)
            self.layout.setObjectName("layout")
            self.layout.addWidget(self.table_right, 0, 0, 200, 50)
            # self.layout.addWidget(self.wincurl, 200, 0, 100, 50)
            self.setLayout(self.layout)
            lindid = 0

            totalwin = 0
            totallost = 0
            winnum = 0
            lostnum = 0
            rate = 0
            id = 0
            with open(indexfilename, 'r') as f:
                for line in f:
                    strlist = line.split(",")
                    if float(strlist[7]) > 1e-7:
                        totalwin = totalwin + float(strlist[7])
                        winnum += 1
                    elif float(strlist[7]) < -1e-7:
                        totallost = totallost + float(strlist[7])
                        lostnum += 1

                    rate = float(winnum) / float(winnum + lostnum)
                    if winnum > 0:
                        winrate = totalwin / winnum
                    else:
                        winrate = 0
                    if winnum > 0:
                        lostrate = totallost / lostnum
                    else:
                        lostrate = 0
                id += 1

            self.table_right.insertRow(lindid)
            item = QTableWidgetItem('%d' % id)
            self.table_right.setItem(lindid, 0, item)
            item = QTableWidgetItem('rb')
            self.table_right.setItem(lindid, 1, item)
            item = QTableWidgetItem('%d' % winnum)
            self.table_right.setItem(lindid, 2, item)
            item = QTableWidgetItem('%d' % lostnum)
            self.table_right.setItem(lindid, 3, item)
            item = QTableWidgetItem('%.2f' % rate)
            self.table_right.setItem(lindid, 4, item)
            item = QTableWidgetItem('%.2f' % winrate)
            self.table_right.setItem(lindid, 5, item)
            item = QTableWidgetItem('%.2f' % lostrate)
            self.table_right.setItem(lindid, 6, item)

            Button_report = QPushButton("查看报告")
            # self.deleteButtonlist.append(self.deleteButton)
            Button_report.clicked.connect(self.Function_OpenAnalysisReport)
            # buttonid = buttonid + 1
            self.table_right.setCellWidget(lindid, 7, Button_report)

    def OnStart(self):
        # tradestate = 0
        # backteststate = 0
        if globalvar.DialogBackTestPoint.backteststate == 0:
            globalvar.tradestate = 1
            self.SetBarRunState(globalvar.tradestate)
            self.Button_Start.setEnabled(False)
            self.Button_Stop.setEnabled(True)
            self.Button_Start.setStyleSheet("QPushButton{border-image: url(onstart2.png)}")
            self.Button_Stop.setStyleSheet("QPushButton{border-image: url(onstop1.png)}")
        else:
            self.autologoutwarnwin = QMessageBox(None)
            self.autologoutwarnwin.setIcon(QMessageBox.Warning)
            self.autologoutwarnwin.setText(('实盘交易前，请先停止回测'))
            self.autologoutwarnwin.setWindowTitle(('说明'))
            self.autologoutwarnwin.setStandardButtons(QMessageBox.Ok)
            self.autologoutwarnwin.exec_()

    def OnStop(self):
        globalvar.tradestate = 0
        self.SetBarRunState(globalvar.tradestate)
        self.Button_Start.setEnabled(True)
        self.Button_Stop.setEnabled(False)
        self.Button_Start.setStyleSheet("QPushButton{border-image: url(onstart1.png)}")
        self.Button_Stop.setStyleSheet("QPushButton{border-image: url(onstop2.png)}")

    # global logname
    # logname = u'20210601'

    def ClearPath(self, path):
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".txt":
                    os.remove(c_path)
                    print("Delete file complete :", c_path)

    def Function_ClearMdLog(self):
        self.ClearPath("log/md")

    def Function_ClearTdLog(self):
        self.ClearPath("log/td")

    # 打开资金曲线对话框
    def Function_OpenCapitalCurve(self):
        ui_demo = self.DialogCapitalCurve()
        ui_demo.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 - 75,
                     (screen.height() - size.height()) / 2 - 50)
        ui_demo.setWindowTitle('添加交易账户')
        ui_demo.show()
        ui_demo.resize(450, 300)
        # self.childwidget = self.childwidget(self)
        # self.childwidget.exec_()
        ui_demo.exec_()

    # 策略说明
    def Function_StrategyInstructions(self):
        webbrowser.open('https://zhuanlan.zhihu.com/p/393090084')

    # 添加合约组
    def Function_AddInstrumentGroup(self):
        webbrowser.open('https://zhuanlan.zhihu.com/p/393090084')

    # 关于合约组
    def Function_AboutInstrumentGroup(self):
        webbrowser.open('https://zhuanlan.zhihu.com/p/393090084')

    # 双击下单
    def Function_doubleClicked_TradeConfirm(self):
        ui_demo = self.DialogTradeConfirm()
        # ui_demo.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 - 75,
                     (screen.height() - size.height()) / 2 - 10)
        ui_demo.setWindowTitle('下单确认')
        ui_demo.show()
        ui_demo.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        ui_demo.exec_()

    # 添加账户
    def Function_AddInvestor(self):
        ui_demo = self.DialogInvestor()
        # ui_demo.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 - 75,
                     (screen.height() - size.height()) / 2 - 10)
        ui_demo.setWindowTitle('添加交易账户')
        ui_demo.show()
        ui_demo.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        ui_demo.exec_()

    # 修改账户
    def Function_ModifyInvestor(self):
        webbrowser.open('https://zhuanlan.zhihu.com/p/382856586')
        '''
        ui_demo = self.DialogInvestor()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 -75,
                  (screen.height() - size.height()) / 2  -50)
        ui_demo.setWindowTitle('修改交易账户')
        ui_demo.show()
        ui_demo.resize(450, 300)
        self.childwidget = self.childwidget(self)
        self.childwidget.exec_()
        '''

    def Function_OpenLog_TD(self):
        pass
        return
        '''
        import subprocess as sp
        programName = "notepad.exe"
        fileName = "log//td//" + '2021' + ".txt"
        sp.Popen([programName, fileName])
        '''

    def Function_OpenLog_MD(self):
        pass
        return
        '''
        import subprocess as sp
        programName = "notepad.exe"
        fileName = "log//md//" + '2021' + ".txt"
        sp.Popen([programName, fileName])
        '''

    def Function_OpenUrl_SIMNOW(self):
        # QtWidgets.QMessageBox.warning(self, "Warning", "输入数据错误，请重新输入！",QMessageBox.Yes)
        self.autologoutwarnwin = QMessageBox(None)
        self.autologoutwarnwin.setIcon(QMessageBox.Warning)
        self.autologoutwarnwin.setText(('上期SIMNOW官网提供CTP模拟账户注册，\n网站只能在工作日白天才能访问。\n\n但模拟交易账户注册成功后，\n和实盘账户交易时间是一致的。'))
        self.autologoutwarnwin.setWindowTitle(('说明'))
        self.autologoutwarnwin.setStandardButtons(QMessageBox.Ok)
        self.buttonOK = self.autologoutwarnwin.button(QMessageBox.Ok)
        self.buttonOK.setText('我知道了,打开上期SIMNOW网站')
        # self.autologoutwarnwin.buttonClicked.connect(self.autologoutwarn_accepted)
        self.autologoutwarnwin.exec_()
        webbrowser.open('http://www.simnow.com.cn/')

    def Function_OpenUrl_VNPY(self):
        webbrowser.open('http://www.vnpy.cn/')

    def Function_OpenUrl_VNTRADER(self):
        webbrowser.open('http://www.vntrader.cn/')

    def Function_OpenUrl_ZHIHU(self):
        webbrowser.open('https://www.zhihu.com/org/vnpy/posts')

    def Function_OpenUrl_ZHIHUVIDEO(self):
        webbrowser.open('https://www.zhihu.com/org/vnpy/zvideos/')

    def Function_OpenUrl_COOLQUANT(self):
        webbrowser.open('http://www.coolquant.cn/')

    def Function_OpenUrl_KAIHU(self):
        webbrowser.open('http://www.kaihucn.cn/')

    def Function_OpenUrl_Plus(self):
        webbrowser.open('http://www.vnpy.cn/qplus.html')

    def Function_OpenUrl_Community(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_OpenUrl_BandPlus(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_OpenUrl_Buyplus(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_FaqKAIHU(self):
        webbrowser.open('https://www.zhihu.com/zvideo/1333746770867236864')

    def Function_OpenDllLog(self):
        self.Button_OpenDll.setChecked(True)
        self.Button_CloseDll.setChecked(False)
        global td, md
        globalvar.md.OpenLog()
        globalvar.td.OpenLog()

    def Function_CloseDllLog(self):
        self.Button_OpenDll.setChecked(False)
        self.Button_CloseDll.setChecked(True)
        global td, md
        globalvar.md.CloseLog()
        globalvar.td.CloseLog()

    def Function_EnableStrategyManage_SingleThread(self):
        self.Button_StrategyManage_SingleThread.setChecked(True)
        self.Button_StrategyManage_MulitProcess.setChecked(False)

    def Function_EnableStrategyManage_MulitProcess(self):
        self.Button_StrategyManage_SingleThread.setChecked(True)
        self.Button_StrategyManage_MulitProcess.setChecked(False)

    def Function_KlineSource_RealTimeTick(self):
        self.Button_KlineSource_RealTimeTick.setChecked(True)
        self.Button_KlineSource_ServerToday.setChecked(False)
        self.Button_KlineSource_ServerMultiday.setChecked(False)
        globalvar.klineserverstate = 0

    def Function_KlineSource_ServerToday(self):
        self.Button_KlineSource_RealTimeTick.setChecked(False)
        self.Button_KlineSource_ServerToday.setChecked(True)
        self.Button_KlineSource_ServerMultiday.setChecked(False)
        globalvar.klineserverstate = 1
        self.GetKlineFromeServer()

    def Function_KlineSource_ServerMultiday(self):
        self.Button_KlineSource_RealTimeTick.setChecked(False)
        self.Button_KlineSource_ServerToday.setChecked(False)
        self.Button_KlineSource_ServerMultiday.setChecked(True)
        globalvar.klineserverstate = 2
        self.GetKlineFromeServer()

    def Function_FaqDevelopmentEnvironment(self):
        webbrowser.open('https://www.zhihu.com/zvideo/1333746770867236864')

    def Function_doubleClicked_algorithmtrading_limit(self):
        """
         作用：双击事件监听，显示被选中的单元格
        """
        # 打印被选中的单元格
        for i in self.table_algorithmtrading.selectedItems():
            print(i.row(), i.column(), i.text())
            # self.setWindowTitle(i.text())

    def Function_doubleClicked_Trade(self):
        """
         作用：双击事件监听，显示被选中的单元格
        """
        # 打印被选中的单元格
        for i in self.table_account.selectedItems():
            print(i.row(), i.column(), i.text())
            # self.setWindowTitle(i.text())

    def Function_doubleClicked_strategy(self):
        """
        作用：双击事件监听，用默认方式打开文件
        """
        for i in self.table_strategy.selectedItems():
            # print(i.row(), i.column(), i.text())
            print(i.text())
            os.system(i.text())
        # 打开合约组合
        '''
        if globalvar.DialogTalibState:
            return
        try:
            if len(globalvar.dict_talibcondition) == 0:
                self.InitReadTalibcondition()
        except Exception as e:
            self.InitReadTalibcondition()

        globalvar.DialogTalibState=True
        self.dlg = self.DialogSetInstrumentID('')
        self.dlg.setWindowTitle('合约组列表')
        self.dlg.show()
        screenRect = QApplication.desktop().screenGeometry()
        self.dlg.resize(0.58 * screenRect.width(), 0.60 * screenRect.height())
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = self.dlg.geometry()
        self.dlg.move((screen.width() - size.width()) / 2,
                                 (screen.height() - size.height()) / 2)
        self.dlg.exec_()
        '''

    # 双击打开历史交易日志
    def Function_doubleClicked_historytd(self):
        """
        作用：双击事件监听，用默认方式打开文件
        """
        for i in self.table_historytd.selectedItems():
            # print(i.row(), i.column(), i.text())
            print(i.text())
            os.system(i.text())

    # 双击打开历史行情日志
    def Function_doubleClicked_historymd(self):
        """
        作用：双击事件监听，用默认方式打开文件
        """
        for i in self.table_historymd.selectedItems():
            # print(i.row(), i.column(), i.text())
            print(i.text())
            os.system(i.text())

    def Function_Buttonclickh1(self):
        try:
            if '最近访问' in self.Button_h[0].text():
                return
            else:
                self.change_comboBox(self.Button_h[0].text())
        except Exception as e:
            print("Function_Buttonclickh1:" + repr(e))

    def Function_Buttonclickh2(self):
        try:
            if '最近访问' in self.Button_h[1].text():
                return
            else:
                self.change_comboBox(self.Button_h[1].text())
        except Exception as e:
            print("Function_Buttonclickh2:" + repr(e))

    def Function_Buttonclickh3(self):
        try:
            if '最近访问' in self.Button_h[2].text():
                return
            else:
                self.change_comboBox(self.Button_h[2].text())
        except Exception as e:
            print("Function_Buttonclickh3:" + repr(e))

    def Function_Buttonclickh4(self):
        try:
            if '最近访问' in self.Button_h[3].text():
                return
            else:
                self.change_comboBox(self.Button_h[3].text())
        except Exception as e:
            print("Function_Buttonclickh4:" + repr(e))

    def Function_Buttonclickh5(self):
        try:
            if '最近访问' in self.Button_h[4].text():
                return
            else:
                self.change_comboBox(self.Button_h[4].text())
        except Exception as e:
            print("Function_Buttonclickh5:" + repr(e))

    def Function_Buttonclickh6(self):
        try:
            if '最近访问' in self.Button_h[5].text():
                return
            else:
                self.change_comboBox(self.Button_h[5].text())
        except Exception as e:
            print("Function_Buttonclickh6:" + repr(e))

    def Function_Buttonclickh7(self):
        try:
            if '最近访问' in self.Button_h[6].text():
                return
            else:
                self.change_comboBox(self.Button_h[6].text())
        except Exception as e:
            print("Function_Buttonclickh7:" + repr(e))

    def Function_Buttonclickh8(self):
        try:
            if '最近访问' in self.Button_h[7].text():
                return
            else:
                self.change_comboBox(self.Button_h[7].text())
        except Exception as e:
            print("Function_Buttonclickh8:" + repr(e))

    def Function_Buttonclickh9(self):
        try:
            if '最近访问' in self.Button_h[8].text():
                return
            else:
                self.change_comboBox(self.Button_h[8].text())
        except Exception as e:
            print("Function_Buttonclickh9:" + repr(e))

    def Function_Buttonclickh10(self):
        try:
            if '最近访问' in self.Button_h[9].text():
                return
            else:
                self.change_comboBox(self.Button_h[9].text())
        except Exception as e:
            print("Function_Buttonclickh10:" + repr(e))

    def Function_Buttonclickh11(self):
        try:
            if '最近访问' in self.Button_h[10].text():
                return
            else:
                self.change_comboBox(self.Button_h[10].text())
        except Exception as e:
            print("Function_Buttonclickh11:" + repr(e))

    def Function_Buttonclickh12(self):
        try:
            if '最近访问' in self.Button_h[11].text():
                return
            else:
                self.change_comboBox(self.Button_h[11].text())
        except Exception as e:
            print("Function_Buttonclickh12:" + repr(e))

    def Function_Buttonclickt1(self):
        try:
            if '最近交易' in self.Button_t[0].text():
                return
            else:
                self.change_comboBox(self.Button_t[0].text())
        except Exception as e:
            print("Function_Buttonclickt1:" + repr(e))

    def Function_Buttonclickt2(self):
        try:
            if '最近交易' in self.Button_t[1].text():
                return
            else:
                self.change_comboBox(self.Button_t[1].text())
        except Exception as e:
            print("Function_Buttonclickt2:" + repr(e))

    def Function_Buttonclickt3(self):
        try:
            if '最近交易' in self.Button_t[2].text():
                return
            else:
                self.change_comboBox(self.Button_t[2].text())
        except Exception as e:
            print("Function_Buttonclickt3:" + repr(e))

    def Function_Buttonclickt4(self):
        try:
            if '最近交易' in self.Button_t[3].text():
                return
            else:
                self.change_comboBox(self.Button_t[3].text())
        except Exception as e:
            print("Function_Buttonclickt4:" + repr(e))

    def Function_Buttonclickt5(self):
        try:
            if '最近交易' in self.Button_t[4].text():
                return
            else:
                self.change_comboBox(self.Button_t[4].text())
        except Exception as e:
            print("Function_Buttonclickt5:" + repr(e))

    def Function_Buttonclickt6(self):
        try:
            if '最近交易' in self.Button_t[5].text():
                return
            else:
                self.change_comboBox(self.Button_t[5].text())
        except Exception as e:
            print("Function_Buttonclickt6:" + repr(e))

    def Function_Buttonclickt7(self):
        try:
            if '最近交易' in self.Button_t[6].text():
                return
            else:
                self.change_comboBox(self.Button_t[6].text())
        except Exception as e:
            print("Function_Buttonclickt7:" + repr(e))

    def Function_Buttonclickt8(self):
        try:
            if '最近交易' in self.Button_t[7].text():
                return
            else:
                self.change_comboBox(self.Button_t[7].text())
        except Exception as e:
            print("Function_Buttonclickt8:" + repr(e))

    def Function_Buttonclickt9(self):
        try:
            if '最近交易' in self.Button_t[8].text():
                return
            else:
                self.change_comboBox(self.Button_t[8].text())
        except Exception as e:
            print("Function_Buttonclickt9:" + repr(e))

    def Function_Buttonclickt10(self):
        try:
            if '最近交易' in self.Button_t[9].text():
                return
            else:
                self.change_comboBox(self.Button_t[9].text())
        except Exception as e:
            print("Function_Buttonclickt10:" + repr(e))

    def Function_Buttonclickt11(self):
        try:
            if '最近交易' in self.Button_t[10].text():
                return
            else:
                self.change_comboBox(self.Button_t[10].text())
        except Exception as e:
            print("Function_Buttonclickt11:" + repr(e))

    def Function_Buttonclickt12(self):
        try:
            if '最近交易' in self.Button_t[11].text():
                return
            else:
                self.change_comboBox(self.Button_t[11].text())
        except Exception as e:
            print("Function_Buttonclickt12:" + repr(e))

    def Function_Buttonclickz1(self):
        try:
            if '自选' in self.Button_zx[0].text():
                return
            else:
                self.change_comboBox(self.Button_zx[0].text())
        except Exception as e:
            print("Function_Buttonclickz1:" + repr(e))

    def Function_Buttonclickz2(self):
        try:
            if '自选' in self.Button_zx[1].text():
                return
            else:
                self.change_comboBox(self.Button_zx[1].text())
        except Exception as e:
            print("Function_Buttonclickz2:" + repr(e))

    def Function_Buttonclickz3(self):
        try:
            if '自选' in self.Button_zx[2].text():
                return
            else:
                self.change_comboBox(self.Button_zx[2].text())
        except Exception as e:
            print("Function_Buttonclickz3:" + repr(e))

    def Function_Buttonclickz4(self):
        try:
            if '自选' in self.Button_zx[3].text():
                return
            else:
                self.change_comboBox(self.Button_zx[3].text())
        except Exception as e:
            print("Function_Buttonclickz4:" + repr(e))

    def Function_Buttonclickz5(self):
        try:
            if '自选' in self.Button_zx[4].text():
                return
            else:
                self.change_comboBox(self.Button_zx[4].text())
        except Exception as e:
            print("Function_Buttonclickz5:" + repr(e))

    def Function_Buttonclickz6(self):
        try:
            if '自选' in self.Button_zx[5].text():
                return
            else:
                self.change_comboBox(self.Button_zx[5].text())
        except Exception as e:
            print("Function_Buttonclickz6:" + repr(e))

    def Function_Buttonclickz7(self):
        try:
            if '自选' in self.Button_zx[6].text():
                return
            else:
                self.change_comboBox(self.Button_zx[6].text())
        except Exception as e:
            print("Function_Buttonclickz7:" + repr(e))

    def Function_Buttonclickz8(self):
        try:
            if '自选' in self.Button_zx[7].text():
                return
            else:
                self.change_comboBox(self.Button_zx[7].text())
        except Exception as e:
            print("Function_Buttonclickz8:" + repr(e))

    def Function_Buttonclickz9(self):
        try:
            if '自选' in self.Button_zx[8].text():
                return
            else:
                self.change_comboBox(self.Button_zx[8].text())
        except Exception as e:
            print("Function_Buttonclickz9:" + repr(e))

    def Function_Buttonclickz10(self):
        try:
            if '自选' in self.Button_zx[9].text():
                return
            else:
                self.change_comboBox(self.Button_zx[9].text())
        except Exception as e:
            print("Function_Buttonclickz10:" + repr(e))

    def Function_Buttonclickz11(self):
        try:
            if '自选' in self.Button_zx[10].text():
                return
            else:
                self.change_comboBox(self.Button_zx[10].text())
        except Exception as e:
            print("Function_Buttonclickz11:" + repr(e))

    def Function_Buttonclickz12(self):
        try:
            if '自选' in self.Button_zx[11].text():
                return
            else:
                self.change_comboBox(self.Button_zx[11].text())
        except Exception as e:
            print("Function_Buttonclickz12:" + repr(e))

    def InitReadTalibcondition(self):
        with open("talib.csv", "r") as f:
            for line in f.readlines():
                line = line.strip('\n')
                strlist = line.split(",")
                try:
                    if len(globalvar.dict_talibcondition[strlist[0]]) == 0:
                        pass
                except Exception as e:
                    globalvar.dict_talibcondition[strlist[0]] = []
                    print("Function_Buttonclicke0 Error:" + repr(e))
                globalvar.dict_talibcondition[strlist[0]].append(strlist)

    def InitReadTalibconditionIni(self):
        import configparser
        conf = configparser.ConfigParser()
        conf.read("./talib.ini")
        sections = conf.sections()
        # 给字典增加key
        for i, j in enumerate(sections):
            # globalvar.dict_talibcondition[i]=[]
            options = conf.options(j)
            globalvar.dict_talibcondition[j] = []
            for m, n in enumerate(options):
                # globalvar.dict_talibcondition[j][m]= conf.get(j, n)
                globalvar.dict_talibcondition[j].append(conf.get(j, n))

        print('nnnnnnnnnnnnnnnnnn：' + str(globalvar.dict_talibcondition, encoding='utf-8'))

    def Function_Buttonclicke0(self):
        if globalvar.DialogTalibState:
            return
        try:
            # print('len(globalvar.dict_talibcondition:'+str(len(globalvar.dict_talibcondition)))
            if len(globalvar.dict_talibcondition) == 0:
                self.InitReadTalibcondition()
        except Exception as e:
            self.InitReadTalibcondition()

        globalvar.DialogTalibState = True
        self.dlg_talibindicatrix = self.DialogTalib()
        self.dlg_talibindicatrix.setWindowTitle('Talib指标条件设置')
        self.dlg_talibindicatrix.show()
        screenRect = QApplication.desktop().screenGeometry()
        self.dlg_talibindicatrix.resize(0.58 * screenRect.width(), 0.60 * screenRect.height())
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = self.dlg_talibindicatrix.geometry()
        self.dlg_talibindicatrix.move((screen.width() - size.width()) / 2,
                                      (screen.height() - size.height()) / 2)
        self.dlg_talibindicatrix.exec_()

    def Function_Buttonclicke1(self):
        dlg_myindicatrix = self.DialogTalib()
        dlg_myindicatrix.setWindowTitle('自定义指标')
        dlg_myindicatrix.show()
        screenRect = QApplication.desktop().screenGeometry()
        dlg_myindicatrix.resize(0.65 * screenRect.width(), 0.65 * screenRect.height())
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = dlg_myindicatrix.geometry()
        dlg_myindicatrix.move((screen.width() - size.width()) / 2,
                              (screen.height() - size.height()) / 2)
        dlg_myindicatrix.exec_()

    def Function_Buttonclicke2(self):
        dlg_talibperiod = self.DialogTalib()
        # dlg_talibperiod.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = dlg_talibperiod.geometry()
        dlg_talibperiod.move((screen.width() - size.width()) / 2 - 75,
                             (screen.height() - size.height()) / 2 - 10)
        dlg_talibperiod.setWindowTitle('Talib指标')
        dlg_talibperiod.show()
        dlg_talibperiod.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        dlg_talibperiod.exec_()

    def Function_Buttonclicke3(self):
        dlg_talibinstrumentid = self.DialogTalib()
        # dlg_talibinstrumentid.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = dlg_talibinstrumentid.geometry()
        dlg_talibinstrumentid.move((screen.width() - size.width()) / 2 - 75,
                                   (screen.height() - size.height()) / 2 - 10)
        dlg_talibinstrumentid.setWindowTitle('Talib指标')
        dlg_talibinstrumentid.show()
        dlg_talibinstrumentid.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        dlg_talibinstrumentid.exec_()
        pass
        '''
        self.Button_e0.setEnabled(True)
        self.Button_e1.setEnabled(True)
        self.Button_e2.setEnabled(True)
        self.Button_e3.setEnabled(False)
        self.Button_e4.setEnabled(True)
        self.Button_e5.setEnabled(True)
        '''

    def Function_Buttonclicke4(self):
        pass

    def Function_Buttonclicke5(self):
        pass
        '''
        self.Button_e0.setEnabled(True)
        self.Button_e5.setEnabled(False)
        '''

    def SetBarRunState(self, state):
        if state == 0:
            self.lab_run.setPixmap(QPixmap('ico_alert_stop.png'))
        elif state == 1:
            self.lab_run.setPixmap(QPixmap('ico_alert_run.png'))

    def SetBarMDState(self, state):
        if state == 1:
            self.lab_md.setPixmap(QPixmap('ico_error_mdconnect.png'))
        elif state == 2:
            self.lab_md.setPixmap(QPixmap('ico_right_mdlogin.png'))
        elif state == 3:
            self.lab_md.setPixmap(QPixmap('ico_right_mdlogin.png'))

    def SetBarTDState(self, state):
        if state == 1:
            self.lab_td.setPixmap(QPixmap('ico_error_tdconnect.png'))
        elif state == 2:
            self.lab_td.setPixmap(QPixmap('ico_right_tdlogin.png'))
        elif state == 3:
            self.lab_td.setPixmap(QPixmap('ico_right_tdlogin.png'))

    def setupUi(self, MainWindow):
        self.MainWindow = MainWindow
        self.MainWindow.setObjectName("MainWindow")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setTabPosition(QtWidgets.QTabWidget.East)
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout = QtWidgets.QGridLayout(self.tab)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.groupBox = QtWidgets.QGroupBox(self.tab)
        self.groupBox.setObjectName("groupBox")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.groupBox)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.toolBox1 = QtWidgets.QToolBox(self.groupBox)

        # 组标题 toolBox1
        self.toolBox1.setObjectName("")

        self.toolBox2 = QtWidgets.QToolBox(self.groupBox)
        self.toolBox2.setObjectName("toolBox2")

        self.page_order = QtWidgets.QWidget()
        self.page_order.setGeometry(QtCore.QRect(0, 0, 98, 44))
        self.page_order.setObjectName("page_order")
        self.gridLayout_instrument = QtWidgets.QGridLayout(self.page_order)
        self.gridLayout_instrument.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrument.setObjectName("gridLayout_instrument")
        """
        #1，1 委托记录
        self.lineEdit = QtWidgets.QLineEdit(self.page_order)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout_instrument.addWidget(self.lineEdit, 0, 0, 1, 1)
        """
        self.table_order = QtWidgets.QTableWidget(self.page_order)
        self.table_order.setObjectName("table_Order")
        self.table_order.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_order.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_order.setEditTriggers(QTableView.NoEditTriggers)
        self.table_order.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_order.setColumnCount(9)
        self.table_order.setRowCount(0)
        self.table_order.setHorizontalHeaderLabels(
            ['报单编号', '合约', '买卖', '开平', '报单状态', '报单数', '已成交手数', '价格', '报单时间', '交易所'])  # 设置表头文字
        self.table_order.setSortingEnabled(True)  # 设置表头可以自动排序

        self.gridLayout_instrument.addWidget(self.table_order, 0, 0, 1, 1)
        self.toolBox1.addItem(self.page_order, "")
        self.page_instrument = QtWidgets.QWidget()
        self.page_instrument.setGeometry(QtCore.QRect(0, 0, 98, 44))
        self.page_instrument.setObjectName("page_instrument")
        self.gridLayout_instrument = QtWidgets.QGridLayout(self.page_instrument)
        self.gridLayout_instrument.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrument.setObjectName("gridLayout_instrument")

        self.table_instrumentcx = QtWidgets.QTableWidget(self.page_instrument)
        self.table_instrumentcx.setObjectName("table_Order")
        self.table_instrumentcx.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_instrumentcx.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_instrumentcx.setEditTriggers(QTableView.NoEditTriggers)
        self.table_instrumentcx.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_instrumentcx.setColumnCount(8)
        self.table_instrumentcx.setRowCount(4)
        self.table_instrumentcx.setHorizontalHeaderLabels(
            ['品种代码', '合约', '合约名', '交易所', '合约乘数', '最小价格变动单位', '保证金', '手续费'])  # 设置表头文字
        self.table_instrumentcx.setSortingEnabled(True)  # 设置表头可以自动排序
        self.gridLayout_instrument.addWidget(self.table_instrumentcx, 0, 0, 1, 1)

        self.toolBox2.addItem(self.page_instrument, "")
        self.page_trade = QtWidgets.QWidget()
        self.page_trade.setGeometry(QtCore.QRect(0, 0, 697, 210))
        self.page_trade.setObjectName("page_trade")
        self.gridLayout_position = QtWidgets.QGridLayout(self.page_trade)
        self.gridLayout_position.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_position.setObjectName("gridLayout_position")

        self.table_trade = QtWidgets.QTableWidget(self.page_trade)
        self.table_trade.setObjectName("table_trade")
        self.table_trade.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_trade.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_trade.setEditTriggers(QTableView.NoEditTriggers)
        self.table_trade.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_trade.doubleClicked.connect(self.Function_doubleClicked_Trade)
        self.table_trade.setColumnCount(11)
        self.table_trade.setRowCount(0)
        self.table_trade.setHorizontalHeaderLabels(
            ['策略名称', '成交编号', '报单编号', '合约', '买卖', '开平', '成交价格', '委托手数', '成交时间', '交易所', '备注'])  # 设置表头文字
        self.table_trade.setSortingEnabled(True)  # 设置表头可以自动排序
        self.gridLayout_position.addWidget(self.table_trade, 1, 1, 1, 1)

        self.page_position = QtWidgets.QWidget()
        self.page_position.setGeometry(QtCore.QRect(0, 0, 697, 210))
        self.page_position.setObjectName("page_position")
        self.gridLayout_position = QtWidgets.QGridLayout(self.page_position)
        self.gridLayout_position.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_position.setObjectName("gridLayout_position")
        self.table_position = QtWidgets.QTableWidget(self.page_trade)
        self.table_position.setObjectName("table_trade")
        self.table_position.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_position.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_position.setEditTriggers(QTableView.NoEditTriggers)
        self.table_position.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_position.setColumnCount(8)
        self.table_position.setRowCount(0)
        self.table_position.setHorizontalHeaderLabels(
            ['合约', '买卖', '总持仓', '今仓', '可平量', '占用保证金', '持仓成本', '持仓盈亏'])  # 设置表头文字
        # 设置行高
        self.table_position.setRowHeight(0, 30)
        self.table_position.setSortingEnabled(True)  # 设置表头可以自动排序
        # self.table_position.sortItems(1,  Qt.DescendingOrder)  # 设置按照第二列自动降序排序
        self.table_position.horizontalHeader().setStretchLastSection(True)  ##设置最后一列拉伸至最大
        # self.table_position.setItemDelegateForColumn(0,  self )  # 设置第0列不可编辑
        self.table_position.doubleClicked.connect(self.Function_doubleClicked_algorithmtrading_limit)

        # TOdo 优化7 在单元格内放置控件
        """
        comBox=QtWidgets.QComboBox()
        comBox.addItems(['卖','买'])
        comBox.setStyleSheet('QComboBox{margin:3px}')
        self.table_position.setCellWidget(0,1,comBox)
        """
        '''

        Trade_CancelBtn = QtWidgets.QPushButton('双击人工平仓')
        Trade_CancelBtn.setFlat(True)
        Trade_CancelBtn.setStyleSheet('background-color:#ff0000;');
        # searchBtn.setDown(True)
        Trade_CancelBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_position.setCellWidget(0, 6, Trade_CancelBtn)
        '''
        self.gridLayout_position.addWidget(self.table_position, 1, 1, 1, 1)
        self.toolBox1.addItem(self.page_trade, "")
        self.toolBox2.addItem(self.page_position, "")
        self.verticalLayout_3.addWidget(self.toolBox1)
        self.verticalLayout_3.addWidget(self.toolBox2)
        self.gridLayout.addWidget(self.groupBox, 1, 0, 1, 1)
        self.tabWidget_2 = QtWidgets.QTabWidget(self.tab)
        self.tabWidget_2.setObjectName("tabWidget_2")

        self.tab_strategy = QtWidgets.QWidget()
        self.tab_strategy.setObjectName("tab_strategy")
        self.tab_instrumentgroup = QtWidgets.QWidget()
        self.tab_instrumentgroup.setObjectName("tab_instrumentgroup")
        self.tab_account = QtWidgets.QWidget()
        self.tab_account.setObjectName("tab_account")
        self.tab_plus = QtWidgets.QWidget()
        self.tab_plus.setObjectName("tab_plus")
        self.tab_marketdata = QtWidgets.QWidget()
        self.tab_marketdata.setObjectName("tab_marketdata")
        self.tab_instrument = QtWidgets.QWidget()
        self.tab_instrument.setObjectName("tab_instrument")
        self.tab_algorithmtrading = QtWidgets.QWidget()
        self.tab_algorithmtrading.setObjectName("tab_algorithmtrading")
        self.tab_listtdlog = QtWidgets.QWidget()
        self.tab_listtdlog.setObjectName("tab_listtdlog")
        self.tab_listmdlog = QtWidgets.QWidget()
        self.tab_listmdlog.setObjectName("tab_listmdlog")
        self.tab_historytd = QtWidgets.QWidget()
        self.tab_historytd.setObjectName("tab_historytd")
        self.tab_historymd = QtWidgets.QWidget()
        self.tab_historymd.setObjectName("tab_historymd")
        self.tab_backtestdata = QtWidgets.QWidget()
        self.tab_backtestdata.setObjectName("tab_backtestdata")

        # self.tab_report = QtWidgets.QWidget()
        # self.tab_report.setObjectName("tab_report")
        self.tab_result = QtWidgets.QWidget()
        self.tab_result.setObjectName("tab_result")

        self.tab_faq = QtWidgets.QWidget()
        self.tab_faq.setObjectName("tab_faq")
        self.tabWidget_2.addTab(self.tab_strategy, "")
        self.tabWidget_2.addTab(self.tab_instrumentgroup, "")
        self.tabWidget_2.addTab(self.tab_account, "")
        self.tabWidget_2.addTab(self.tab_plus, "")
        self.tabWidget_2.addTab(self.tab_marketdata, "")
        self.tabWidget_2.addTab(self.tab_instrument, "")
        self.tabWidget_2.addTab(self.tab_algorithmtrading, "")
        self.tabWidget_2.addTab(self.tab_listtdlog, "")
        self.tabWidget_2.addTab(self.tab_listmdlog, "")
        self.tabWidget_2.addTab(self.tab_historytd, "")
        self.tabWidget_2.addTab(self.tab_historymd, "")
        self.tabWidget_2.addTab(self.tab_backtestdata, "")
        # self.tabWidget_2.addTab(self.tab_report, "")
        self.tabWidget_2.addTab(self.tab_result, "")
        self.tabWidget_2.addTab(self.tab_faq, "")

        self.Button_AddStrategy = QPushButton("重新扫描策略目录")
        self.Button_OpenStrategyPath = QPushButton("打开策略目录")
        self.Button_ConditionCombination = QPushButton("指标条件组合策略(升级中)")
        self.Button_TalibCondition = QPushButton("Talib指标条件设置(升级中)")
        self.Button_AddInstrumentGroup = QPushButton("添加合约组")
        self.Button_AboutInstrumentGroup = QPushButton("关于合约组")
        self.Button_StrategyInstructions = QPushButton("策略模块使用说明")
        self.Button_StrategyFunction = QPushButton("")
        self.Button_AddInvestor = QPushButton("添加或修改账户")
        self.Button_ModifyInvestor = QPushButton("如何申请穿透监管授权码")
        self.Button_AddInstrument = QPushButton("添加合约编码")
        self.Button_SelectMainInstrument = QPushButton("选择主力合约")
        self.Button_SelectAll = QPushButton("全部选择")
        self.Button_SelectNone = QPushButton("全部不选")
        self.Button_Simnow = QPushButton("注册模拟账户（仅限工作日白天）")
        self.Button_Kaihu = QPushButton("开立实盘账户")
        self.Button_Plus = QPushButton("Plus会员说明")
        self.Button_Community = QPushButton("社区登录注册")
        self.Button_BandPlus = QPushButton("绑定期货账号获取Plus")
        self.Button_Buyplus = QPushButton("购买Plus")
        self.Button_OpenBackTestingPath = QPushButton("打开回测报告目录")
        self.Button_SetServiceUser = QPushButton("设置数据会员账户")
        self.Button_BuyService = QPushButton("购买数据服务会员")
        self.Button_ClearTdLog = QPushButton("清除历史交易日志文件")
        self.Button_ClearMdLog = QPushButton("清除历史行情日志文件")
        self.Button_ClearTodayTdLog = QPushButton("清空今日交易日志")
        self.Button_ClearTodayMdLog = QPushButton("清空今日行情日志")
        self.Button_OpenAlgorithmicTradingPath = QPushButton("打开算法交易目录")
        self.Button_FaqKaihu = QPushButton("如何降低交易成本")
        self.Button_FaqDevelopmentEnvironment = QPushButton("开发环境")
        self.Button_Faq3 = QPushButton("FAQ3")
        self.Button_Faq4 = QPushButton("FAQ4")
        self.Button_Faq5 = QPushButton("FAQ5")
        self.Button_Faq6 = QPushButton("FAQ6")
        self.Button_Faq7 = QPushButton("FAQ7")
        self.Button_Faq8 = QPushButton("FAQ8")
        self.Button_Faq9 = QPushButton("FAQ9")
        self.Button_Faq10 = QPushButton("FAQ10")
        self.Button_Faq11 = QPushButton("FAQ11")
        self.Button_Faq12 = QPushButton("FAQ12")
        self.Button_Faq13 = QPushButton("FAQ13")
        self.Button_Faq14 = QPushButton("FAQ14")

        self.gridLayout_strategy = QtWidgets.QGridLayout(self.tab_strategy)
        self.gridLayout_strategy.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_strategy.setObjectName("gridLayout_strategy")

        self.gridLayout_instrumentgroup = QtWidgets.QGridLayout(self.tab_instrumentgroup)
        self.gridLayout_instrumentgroup.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrumentgroup.setObjectName("gridLayout_instrumentgroup")

        self.gridLayout_account = QtWidgets.QGridLayout(self.tab_account)
        self.gridLayout_account.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_account.setObjectName("gridLayout_account")

        self.table_account = QtWidgets.QTableWidget(self.tab_account)
        self.table_account.setObjectName("table_account")
        self.table_account.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_account.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_account.setColumnCount(10)
        self.table_account.setRowCount(1)
        self.table_account.setEditTriggers(QTableView.NoEditTriggers)
        self.table_account.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_account.setHorizontalHeaderLabels(
            ['期货公司BrokeID', '期货账户', '静态权益', '动态权益', '收益率', '可用资金', '仓位(风险度)', '手续费', '可取资金', '上次更新时间'])

        self.table_account.setColumnWidth(0, 120)
        self.table_account.setColumnWidth(4, 80)
        self.table_account.setColumnWidth(6, 80)
        self.table_account.setColumnWidth(9, 140)

        try:
            global config
            config = configparser.ConfigParser()
            # -read读取ini文件
            config.read('vnctptd.ini', encoding='utf-8')
            brokeid = config.get('setting', 'brokeid')
            investor = config.get('setting', 'investor')
            password = config.get('setting', 'password')
            appid = config.get('setting', 'appid')
            userproductinfo = config.get('setting', 'userproductinfo')
            authcode = config.get('setting', 'authcode')
            address1 = config.get('setting', 'address1')
            address2 = config.get('setting', 'address2')
            address3 = config.get('setting', 'address3')
            item = QTableWidgetItem(brokeid)
            self.table_account.setItem(0, 0, item)
            item = QTableWidgetItem(investor)
            self.table_account.setItem(0, 1, item)
            item = QTableWidgetItem('登录更新')  # 静态权益
            self.table_account.setItem(0, 2, item)
            item = QTableWidgetItem('登录更新')
            self.table_account.setItem(0, 3, item)
            item = QTableWidgetItem('0.0%')  # 今日盈亏
            self.table_account.setItem(0, 4, item)
            item = QTableWidgetItem('登录更新')
            self.table_account.setItem(0, 5, item)  # 可用权益
            item = QTableWidgetItem('登录更新')  # 仓位
            self.table_account.setItem(0, 6, item)
            item = QTableWidgetItem('登录更新')  # 手续费
            self.table_account.setItem(0, 7, item)
            item = QTableWidgetItem('登录更新')  # 可取资金
            self.table_account.setItem(0, 8, item)
            item = QTableWidgetItem('登录更新')
            self.table_account.setItem(0, 9, item)
        except Exception as e:
            print("login Error:" + repr(e))

        # tab_instrument

        self.gridLayout_instrument = QtWidgets.QGridLayout(self.tab_instrument)
        self.gridLayout_instrument.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrument.setObjectName("gridLayout_tab_instrument")

        self.table_instrument = QtWidgets.QTableWidget(self.tab_instrument)
        self.table_instrument.setObjectName("table_instrument")
        self.table_instrument.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_instrument.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_instrument.setEditTriggers(QTableView.NoEditTriggers)
        self.table_instrument.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_instrument.doubleClicked.connect(self.Function_doubleClicked_Trade)
        self.table_instrument.setColumnCount(7)
        self.table_instrument.setRowCount(0)
        self.table_instrument.setHorizontalHeaderLabels(
            ['ID', '合约', '合约编码', '交易所', '1跳价差', '保证金', '手续费'])  # 设置表头文字
        self.table_instrument.setSortingEnabled(True)  # 设置表头可以自动排序
        self.gridLayout_instrument.addWidget(self.table_instrument, 0, 0, 2, 2)
        self.gridLayout_instrument.addWidget(self.Button_AddInstrument, 1, 0, 1, 1)
        self.gridLayout_instrument.addWidget(self.Button_SelectMainInstrument, 1, 1, 1, 1)
        self.gridLayout_instrument.addWidget(self.Button_SelectAll, 2, 0, 1, 1)
        self.gridLayout_instrument.addWidget(self.Button_SelectNone, 2, 1, 1, 1)

        # list_marketdata
        self.gridLayout_marketdata = QtWidgets.QGridLayout(self.tab_marketdata)
        self.gridLayout_marketdata.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_marketdata.setObjectName("gridLayout_marketdata")
        self.list_marketdata = QtWidgets.QListWidget(self.tab_marketdata)
        self.list_marketdata.setObjectName("list_marketdata")
        _translate = QtCore.QCoreApplication.translate
        __sortingEnabled = self.list_marketdata.isSortingEnabled()
        self.list_marketdata.setSortingEnabled(False)
        self.list_marketdata.setSortingEnabled(__sortingEnabled)
        self.gridLayout_marketdata.addWidget(self.list_marketdata, 0, 0, 1, 1)

        # 今日交易日志
        self.gridLayout_listtdlog = QtWidgets.QGridLayout(self.tab_listtdlog)
        self.gridLayout_listtdlog.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_listtdlog.setObjectName("gridLayout_listtdlog")
        self.list_listtdlog = QtWidgets.QListWidget(self.tab_listtdlog)
        self.list_listtdlog.setObjectName("list_listtdlog")
        _translate = QtCore.QCoreApplication.translate
        __sortingEnabled = self.list_listtdlog.isSortingEnabled()
        self.list_listtdlog.setSortingEnabled(False)
        self.list_listtdlog.setSortingEnabled(__sortingEnabled)
        self.gridLayout_listtdlog.addWidget(self.list_listtdlog, 0, 0, 1, 1)
        self.gridLayout_listtdlog.addWidget(self.Button_ClearTodayTdLog, 1, 0, 1, 1)

        # 今日行情日志
        self.gridLayout_listmdlog = QtWidgets.QGridLayout(self.tab_listmdlog)
        self.gridLayout_listmdlog.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_listmdlog.setObjectName("gridLayout_listmdlog")
        self.list_listmdlog = QtWidgets.QListWidget(self.tab_listmdlog)
        self.list_listmdlog.setObjectName("list_listmdlog")
        _translate = QtCore.QCoreApplication.translate
        __sortingEnabled = self.list_listmdlog.isSortingEnabled()
        self.list_listmdlog.setSortingEnabled(False)
        self.list_listmdlog.setSortingEnabled(__sortingEnabled)
        self.gridLayout_listmdlog.addWidget(self.list_listmdlog, 0, 0, 1, 1)
        self.gridLayout_listmdlog.addWidget(self.Button_ClearTodayMdLog, 1, 0, 1, 1)

        # 增值服务
        self.gridLayout_plus = QtWidgets.QGridLayout(self.tab_plus)
        self.gridLayout_plus.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_plus.setObjectName("gridLayout_plus")
        self.table_plus = QtWidgets.QTableWidget(self.tab_plus)
        self.table_plus.setObjectName("table_plus")
        self.table_plus.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_plus.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_plus.setColumnCount(7)
        self.table_plus.setRowCount(0)
        self.table_plus.setEditTriggers(QTableView.NoEditTriggers)
        self.table_plus.setHorizontalHeaderLabels(
            ['期货版Plus会员', '积分', '推荐人数', '多日K线数据', '有限期', '回测功能', '有效期'])  # 设置表头文字
        self.table_plus.setColumnWidth(0, 150)
        self.table_plus.setColumnWidth(1, 120)
        self.table_plus.setColumnWidth(2, 120)
        self.table_plus.setColumnWidth(3, 150)
        self.table_plus.setColumnWidth(4, 150)
        self.table_plus.setRowHeight(0, 30)
        Trade_InstrumentBtn = QtWidgets.QPushButton('合约设置')
        Trade_InstrumentBtn.setFlat(True)
        Trade_InstrumentBtn.setStyleSheet('background-color:#ff0000;')
        Trade_InstrumentBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_plus.setCellWidget(0, 6, Trade_InstrumentBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('回测')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_plus.setCellWidget(0, 7, Trade_BacktestingBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('查看策略仓位')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.gridLayout_plus.addWidget(self.table_plus, 0, 0, 2, 2)
        self.gridLayout_plus.addWidget(self.Button_Plus, 1, 0, 1, 1)
        self.gridLayout_plus.addWidget(self.Button_Community, 1, 1, 1, 1)
        self.gridLayout_plus.addWidget(self.Button_BandPlus, 2, 0, 1, 1)
        self.gridLayout_plus.addWidget(self.Button_Buyplus, 2, 1, 1, 1)

        # 策略
        self.table_strategy = QtWidgets.QTableWidget(self.tab_strategy)
        self.table_strategy.setObjectName("table_strategy")
        self.table_strategy.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_strategy.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_strategy.setColumnCount(7)
        self.table_strategy.setRowCount(0)
        self.table_strategy.setEditTriggers(QTableView.NoEditTriggers)
        # self.table_strategy.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_strategy.setHorizontalHeaderLabels(
            ['ID(勾选执行)', '策略文件名称(双击编辑)', '仓位', '今日交易', '操作1', '操作2', '操作3'])  # 设置表头文字
        self.table_strategy.doubleClicked.connect(self.Function_doubleClicked_strategy)
        self.table_strategy.setColumnWidth(1, 290)
        self.table_strategy.setRowHeight(0, 30)
        Trade_InstrumentBtn = QtWidgets.QPushButton('合约设置')
        Trade_InstrumentBtn.setFlat(True)
        Trade_InstrumentBtn.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_InstrumentBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_strategy.setCellWidget(0, 6, Trade_InstrumentBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('回测')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_strategy.setCellWidget(0, 7, Trade_BacktestingBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('查看策略仓位')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_strategy.setCellWidget(0, 8, Trade_BacktestingBtn)
        self.gridLayout_strategy.addWidget(self.table_strategy, 0, 0, 2, 2)
        self.gridLayout_strategy.addWidget(self.Button_AddStrategy, 1, 0, 1, 1)
        self.gridLayout_strategy.addWidget(self.Button_OpenStrategyPath, 1, 1, 1, 1)
        self.gridLayout_strategy.addWidget(self.Button_ConditionCombination, 2, 0, 1, 1)
        self.gridLayout_strategy.addWidget(self.Button_TalibCondition, 2, 1, 1, 1)
        self.table_instrumentgroup = QtWidgets.QTableWidget(self.tab_instrumentgroup)
        self.table_instrumentgroup.setObjectName("table_instrumentgroup")
        self.table_instrumentgroup.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_instrumentgroup.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_instrumentgroup.setColumnCount(5)
        self.table_instrumentgroup.setRowCount(0)
        self.table_instrumentgroup.setEditTriggers(QTableView.NoEditTriggers)
        self.table_instrumentgroup.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_instrumentgroup.setHorizontalHeaderLabels(
            ['ID', '合约组名称', '选入合约数量', '备注', '操作'])  # 设置表头文字
        self.table_instrumentgroup.doubleClicked.connect(self.Function_doubleClicked_strategy)
        self.table_instrumentgroup.setColumnWidth(1, 290)
        self.table_instrumentgroup.setColumnWidth(4, 220)
        self.table_instrumentgroup.setRowHeight(0, 30)
        self.gridLayout_instrumentgroup.addWidget(self.table_instrumentgroup, 0, 0, 1, 2)
        self.gridLayout_instrumentgroup.addWidget(self.Button_AddInstrumentGroup, 1, 0, 1, 1)
        self.gridLayout_instrumentgroup.addWidget(self.Button_AboutInstrumentGroup, 1, 1, 1, 1)

        self.gridLayout_account.addWidget(self.table_account, 0, 0, 2, 2)
        self.gridLayout_account.addWidget(self.Button_AddInvestor, 1, 0, 1, 1)
        self.gridLayout_account.addWidget(self.Button_ModifyInvestor, 1, 1, 1, 1)
        self.gridLayout_account.addWidget(self.Button_Kaihu, 2, 0, 1, 1)
        self.gridLayout_account.addWidget(self.Button_Simnow, 2, 1, 1, 1)

        # 常见问题
        self.gridLayout_faq = QtWidgets.QGridLayout(self.tab_faq)
        self.gridLayout_faq.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_faq.setObjectName("gridLayout_faq")
        self.gridLayout_faq.addWidget(self.Button_FaqKaihu, 0, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_FaqDevelopmentEnvironment, 0, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq3, 1, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq4, 1, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq5, 2, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq6, 2, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq7, 3, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq8, 3, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq9, 4, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq10, 4, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq11, 5, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq12, 5, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq13, 6, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq14, 6, 1, 1, 1)

        # 算法交易
        self.gridLayout_algorithmtrading = QtWidgets.QGridLayout(self.tab_algorithmtrading)
        self.gridLayout_algorithmtrading.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_algorithmtrading.setObjectName("gridLayout_algorithmtrading")
        self.gridLayout.addWidget(self.tabWidget_2, 0, 0, 1, 1)
        self.gridLayout_historytd = QtWidgets.QGridLayout(self.tab_historytd)
        self.gridLayout_historytd.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_historytd.setObjectName("gridLayout_historytd")
        self.gridLayout_historymd = QtWidgets.QGridLayout(self.tab_historymd)
        self.gridLayout_historymd.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_historymd.setObjectName("gridLayout_historymd")
        self.gridLayout_backtestdata = QtWidgets.QGridLayout(self.tab_backtestdata)
        self.gridLayout_backtestdata.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_backtestdata.setObjectName("gridLayout_backtestdata")

        self.table_backtestdata = QtWidgets.QTableWidget(self.tab_backtestdata)
        self.table_backtestdata.setObjectName("table_backtestdata")
        self.table_backtestdata.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_backtestdata.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_backtestdata.setColumnCount(8)
        self.table_backtestdata.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
        self.table_backtestdata.setEditTriggers(QTableView.NoEditTriggers)
        self.table_backtestdata.setHorizontalHeaderLabels(
            ['ID', '合约', '开始日期', '结束日期', '数据大小', '周期', '进度', '操作'])  # 设置表头文字
        self.table_backtestdata.setRowHeight(0, 30)
        self.table_backtestdata.setColumnWidth(0, 50)
        self.table_backtestdata.setColumnWidth(1, 130)
        self.table_backtestdata.setColumnWidth(4, 60)
        self.table_backtestdata.setColumnWidth(5, 60)
        self.table_backtestdata.setColumnWidth(6, 230)
        '''
        Trade_DownloadData = QtWidgets.QPushButton('下载数据')
        Trade_DownloadData.setFlat(True)
        Trade_DownloadData.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_DownloadData.setStyleSheet('QPushButton{margin:3px}')
        self.table_backtestdata.setCellWidget(0, 6, Trade_DownloadData)
        # Trade_DownloadData.triggered.connect(self.Function_OpenUrl_COOLQUANT)
        Trade_DownloadData.clicked.connect(self.OnStart)
        '''
        self.gridLayout_backtestdata.addWidget(self.table_backtestdata, 0, 0, 2, 2)
        self.gridLayout_backtestdata.addWidget(self.Button_SetServiceUser, 1, 0, 1, 1)
        self.gridLayout_backtestdata.addWidget(self.Button_BuyService, 1, 1, 1, 1)

        # --------------------------------------
        # 历史交易日志标签
        self.table_historytd = QtWidgets.QTableWidget(self.tab_historytd)
        self.table_historytd.setObjectName("table_historytd")
        self.table_historytd.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_historytd.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_historytd.setColumnCount(3)
        self.table_historytd.setRowCount(0)
        self.table_historytd.setEditTriggers(QTableView.NoEditTriggers)
        self.table_historytd.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_historytd.setRowHeight(0, 30)
        self.table_historytd.setColumnWidth(0, 100)
        self.table_historytd.setColumnWidth(1, 400)
        self.table_historytd.setHorizontalHeaderLabels(
            ['ID', '文件（文件名为日期，双击打开日志）', '操作'])  # 设置表头文字
        self.table_historytd.doubleClicked.connect(self.Function_doubleClicked_historytd)
        # self.Trade_historytdBtn = QPushButton("打开日志")
        # self.table_historytd.setCellWidget(0, 6, self.Trade_historytdBtn)
        # self.Trade_historytdBtn.clicked.connect(self.Function_OpenLog_TD)
        self.gridLayout_historytd.addWidget(self.table_historytd, 0, 0, 1, 1)
        self.gridLayout_historytd.addWidget(self.Button_ClearTdLog, 1, 0, 1, 1)
        self.Button_ClearTdLog.clicked.connect(self.Function_ClearTdLog)

        self.gridLayout_result = QtWidgets.QGridLayout(self.tab_result)
        self.gridLayout_result.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_result.setObjectName("gridLayout_result")
        self.table_result = QtWidgets.QTableWidget(self.tab_result)
        self.table_result.setObjectName("table_result")
        self.table_result.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_result.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_result.setColumnCount(9)
        self.table_result.setRowCount(0)
        self.table_result.setEditTriggers(QTableView.NoEditTriggers)
        self.table_result.setHorizontalHeaderLabels(
            ['ID', '策略', '执行合约数', '胜率', '盈亏比', '今日交易', '合约设置', '回测', '查看策略仓位'])  # 设置表头文字
        # 设置行高
        self.table_result.setRowHeight(0, 30)
        self.gridLayout_result.addWidget(self.table_result, 0, 0, 2, 2)

        '''
        self.table_report = QtWidgets.QTableWidget(self.tab_report)
        self.table_report.setObjectName("table_result")
        self.table_report.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_report.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_report.setColumnCount(13)
        self.table_report.setRowCount(0)
        self.table_report.setEditTriggers(self.table_report.NoEditTriggers)
        self.table_report.setHorizontalHeaderLabels(
            ['ID', '策略', '回测周期', '合约', '完成进度', '参数1', '步长1', '参数2', '步长2', '参数3', '步长3', '参数4', '步长4'])  # 设置表头文字
        self.table_report.setColumnWidth(0, 90)
        self.table_report.setColumnWidth(1, 110)
        self.table_report.setColumnWidth(4, 110)
        self.table_report.setColumnWidth(5, 70)
        self.table_report.setColumnWidth(6, 70)
        self.table_report.setColumnWidth(7, 70)
        self.table_report.setColumnWidth(8, 70)
        self.table_report.setColumnWidth(9, 70)
        self.table_report.setColumnWidth(10, 70)
        self.table_report.setColumnWidth(11, 70)
        self.table_report.setColumnWidth(12, 70)
        # 设置行高
        self.table_report.setRowHeight(0, 30)
        self.gridLayout_report.addWidget(self.table_report, 0, 0, 2, 2)
        '''

        # 历史行情日志标签
        self.table_historymd = QtWidgets.QTableWidget(self.tab_historymd)
        self.table_historymd.setObjectName("table_historymd")
        self.table_historymd.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_historymd.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_historymd.setColumnCount(3)
        self.table_historymd.setRowCount(0)
        self.table_historymd.setEditTriggers(QTableView.NoEditTriggers)
        self.table_historymd.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_historymd.setRowHeight(0, 30)
        self.table_historymd.setColumnWidth(0, 100)
        self.table_historymd.setColumnWidth(1, 400)
        self.table_historymd.setHorizontalHeaderLabels(
            ['ID', '文件（文件名为日期，双击打开日志）', '操作'])  # 设置表头文字
        self.table_historymd.doubleClicked.connect(self.Function_doubleClicked_historymd)
        self.Trade_historymdBtn = QPushButton("打开日志")
        self.table_historymd.setCellWidget(0, 6, self.Trade_historymdBtn)
        self.Trade_historymdBtn.clicked.connect(self.Function_OpenLog_MD)
        self.gridLayout_historymd.addWidget(self.table_historymd, 0, 0, 1, 1)
        self.gridLayout_historymd.addWidget(self.Button_ClearMdLog, 1, 0, 1, 1)
        self.Button_ClearMdLog.clicked.connect(self.Function_ClearMdLog)

        # 算法交易
        self.table_algorithmtrading = QtWidgets.QTableWidget(self.tab_algorithmtrading)
        self.table_algorithmtrading.setObjectName("table_algorithmtrading")
        self.table_algorithmtrading.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_algorithmtrading.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_algorithmtrading.setColumnCount(7)
        self.table_algorithmtrading.setRowCount(1)
        self.table_algorithmtrading.setRowHeight(0, 30)
        self.table_algorithmtrading.setEditTriggers(QTableView.NoEditTriggers)
        self.table_algorithmtrading.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_algorithmtrading.setHorizontalHeaderLabels(
            ['交易算法', '算法交易路径', '节省滑点', '参数1', '参数2', '参数3', '参数4'])  # 设置表头文字
        self.gridLayout_algorithmtrading.addWidget(self.table_algorithmtrading, 0, 0, 1, 1)
        self.gridLayout_algorithmtrading.addWidget(self.Button_OpenAlgorithmicTradingPath, 1, 0, 1, 1)
        self.Button_OpenAlgorithmicTradingPath.clicked.connect(self.Function_OpenAlgorithmicTradingPath)
        self.table_algorithmtrading.doubleClicked.connect(self.Function_doubleClicked_algorithmtrading_limit)

        def function_item_clicked(self, QTableWidgetItem):
            check_state = QTableWidgetItem.checkState()
            row = QTableWidgetItem.row()
            if check_state == QtCore.Qt.Checked:
                if row not in self.delete_row:
                    self.delete_row.append(row)
            elif check_state == QtCore.Qt.Unchecked:
                if row in self.delete_row:
                    self.delete_row.remove(row)

        item = QTableWidgetItem(' 限价单')
        item.setCheckState(QtCore.Qt.Checked)
        # item.connect(self.table_algorithmtrading, QtCore.SIGNAL("itemClicked(QTableWidgetItem*)"), self.function_item_clicked)
        self.table_algorithmtrading.setItem(0, 0, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(0, 1, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(0, 2, item)
        '''
        item = QTableWidgetItem(' TWAP')
        item.setCheckState(QtCore.Qt.Unchecked)
        self.table_algorithmtrading.setItem(1, 0, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(1, 1, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(1, 2, item)
        '''

        """
        self.dateEdit = QtWidgets.QDateEdit(self.tab)
        self.dateEdit.setObjectName("dateEdit")
        self.gridLayout.addWidget(self.dateEdit, 2, 0, 1, 1)
        """
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.tab_2)
        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.groupBox_2 = QtWidgets.QGroupBox(self.tab_2)
        self.groupBox_2.setObjectName("groupBox_2")
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.groupBox_2)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label = QtWidgets.QLabel(self.groupBox_2)
        self.label.setObjectName("label")
        self.verticalLayout_4.addWidget(self.label)
        self.radioButton = QtWidgets.QRadioButton(self.groupBox_2)
        self.radioButton.setObjectName("radioButton")
        self.verticalLayout_4.addWidget(self.radioButton)
        self.checkBox = QtWidgets.QCheckBox(self.groupBox_2)
        self.checkBox.setObjectName("checkBox")
        self.verticalLayout_4.addWidget(self.checkBox)
        self.checkBox_2 = QtWidgets.QCheckBox(self.groupBox_2)
        self.checkBox_2.setTristate(True)
        self.checkBox_2.setObjectName("checkBox_2")
        self.verticalLayout_4.addWidget(self.checkBox_2)
        self.treeWidget = QtWidgets.QTreeWidget(self.groupBox_2)
        self.treeWidget.setObjectName("treeWidget")
        item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)
        item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)
        self.verticalLayout_4.addWidget(self.treeWidget)
        self.gridLayout_2.addWidget(self.groupBox_2, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab_2, "")
        # addWidget 可控制开始按钮的高度
        self.verticalLayout_5.addWidget(self.tabWidget, 16)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.menu_b_popup = QtWidgets.QToolButton(self.centralwidget)
        self.menu_b_popup.setPopupMode(QtWidgets.QToolButton.InstantPopup)
        self.menu_b_popup.setObjectName("menu_b_popup")
        self.horizontalLayout.addWidget(self.menu_b_popup)

        self.Button_Start = QtWidgets.QPushButton(self.centralwidget)
        self.Button_Start.setObjectName("Button_Start")

        self.Button_Start.setSizePolicy(
            QtGui.QSizePolicy.Preferred,
            QtGui.QSizePolicy.Expanding)
        self.Button_Start.resize(15, 50)
        self.horizontalLayout.addWidget(self.Button_Start)
        # self.Button_Start.setStyleSheet('border-width: 1px;border-style: solid;border-color: rgb(200, 200, 200);background-color: rgb(29, 220, 0);')
        self.Button_Start.setStyleSheet("QPushButton{border-image: url(onstart1.png)}")

        # self.menu_a_popup = QtWidgets.QToolButton(self.centralwidget)
        # self.menu_a_popup.setObjectName("menu_a_popup")
        # self.horizontalLayout.addWidget(self.menu_a_popup)

        # self.menu_c_popup = QtWidgets.QToolButton(self.centralwidget)
        # self.menu_c_popup.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup)
        # self.menu_c_popup.setObjectName("menu_c_popup")
        # self.horizontalLayout.addWidget(self.menu_c_popup)
        # self.line_2 = QtWidgets.QFrame(self.centralwidget)
        # self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
        # self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        # self.line_2.setObjectName("line_2")
        # self.horizontalLayout.addWidget(self.line_2)
        self.Button_Stop = QtWidgets.QPushButton(self.centralwidget)
        self.Button_Stop.setEnabled(False)
        self.Button_Stop.setObjectName("Button_Stop")
        self.Button_Stop.setSizePolicy(
            QtGui.QSizePolicy.Preferred,
            QtGui.QSizePolicy.Expanding)
        self.Button_Stop.setStyleSheet("QPushButton{border-image: url(onstop2.png)}")
        self.horizontalLayout.addWidget(self.Button_Stop)

        self.lab_run = QLabel()
        self.lab_run.setPixmap(QPixmap('ico_alert_stop.png'))
        self.horizontalLayout.addWidget(self.lab_run)

        self.lab_md = QLabel()
        self.lab_md.setPixmap(QPixmap('ico_error_mdconnect.png'))
        self.horizontalLayout.addWidget(self.lab_md)

        self.lab_td = QLabel()
        self.lab_td.setPixmap(QPixmap('ico_error_tdconnect.png'))
        self.horizontalLayout.addWidget(self.lab_td)

        '''
        self.label_1 = QLabel()
        self.label_1.setPixmap(QPixmap('error.png'))
        self.label_1.setText("行情已连接，未登录")
        self.label_1.setAutoFillBackground(True)
        self.palette = QPalette()
        self.palette.setColor(QPalette.Window, Qt.blue)
        self.label_1.setPalette(self.palette)
        self.label_1.setAlignment(Qt.AlignCenter)
        self.horizontalLayout.addWidget(self.label_1)
        '''

        # self.doubleSpinBox = QtWidgets.QDoubleSpinBox(self.centralwidget)
        # self.doubleSpinBox.setObjectName("doubleSpinBox")
        # self.horizontalLayout.addWidget(self.doubleSpinBox)
        self.toolButton = QtWidgets.QToolButton(self.centralwidget)
        self.toolButton.setPopupMode(QtWidgets.QToolButton.InstantPopup)
        self.toolButton.setObjectName("toolButton")
        self.horizontalLayout.addWidget(self.toolButton)
        self.verticalLayout_5.addLayout(self.horizontalLayout, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1068, 23))
        self.menubar.setObjectName("menubar")
        self.menuMenu_nav1 = QtWidgets.QMenu(self.menubar)
        self.menuMenu_nav1.setObjectName("menuMenu")

        self.menuMenu_nav2 = QtWidgets.QMenu(self.menubar)
        self.menuMenu_nav2.setObjectName("menuMenub")

        self.menuMenu_nav3 = QtWidgets.QMenu(self.menubar)
        self.menuMenu_nav3.setObjectName("menuMenub")

        self.menuSubmenu_2 = QtWidgets.QMenu(self.menuMenu_nav1)
        self.menuSubmenu_2.setObjectName("menuSubmenu_2")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.dockWidget1 = QtWidgets.QDockWidget(MainWindow)
        self.dockWidget1.setObjectName("dockWidget1")
        # self.dockWidget1.setFixedSize(800, QDesktopWidget().availableGeometry().height() - 20)  # 分别为宽度和高度

        MainWindow.setFixedSize(QDesktopWidget().availableGeometry().width(),
                                QDesktopWidget().availableGeometry().height())

        self.dockWidgetContents = QtWidgets.QWidget()
        self.dockWidgetContents.setObjectName("dockWidgetContents")

        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.dockWidgetContents)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.comboBox_kline = QtWidgets.QComboBox()
        # self.comboBox_kline.setFixedWidth(180)
        self.comboBox_kline.setObjectName("comboBox_kline")
        self.comboBox_kline.setFixedWidth(180)
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.verticalLayout.addWidget(self.comboBox_kline)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_exchange = QtWidgets.QComboBox()
        self.comboBox_exchange.setFixedWidth(180)
        self.comboBox_exchange.setObjectName("comboBox_exchange")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.verticalLayout.addWidget(self.comboBox_exchange)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_instrument = QtWidgets.QComboBox()
        self.comboBox_instrument.setFixedWidth(180)
        self.comboBox_instrument.setObjectName("comboBox_instrument")
        self.comboBox_instrument.addItem("选择合约类型编码")
        self.verticalLayout.addWidget(self.comboBox_instrument)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_instrumentid = QtWidgets.QComboBox()
        self.comboBox_instrumentid.setFixedWidth(180)
        self.comboBox_instrumentid.setObjectName("comboBox_instrumentid")

        self.comboBox_kline.activated.connect(lambda: self.to_comboBox_klineperiod(self.comboBox_kline.currentText()))
        self.comboBox_exchange.activated.connect(lambda: self.to_comboBox_1(self.comboBox_exchange.currentText()))
        self.comboBox_instrument.activated.connect(lambda: self.to_comboBox_2(self.comboBox_instrument.currentText()))
        self.comboBox_instrumentid.activated.connect(
            lambda: self.to_comboBox_3(self.comboBox_instrumentid.currentText()))

        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.frame_comboBox = QtWidgets.QFrame(self.comboBox_kline)
        self.frame_comboBox.setMinimumSize(QtCore.QSize(0, 0))
        self.frame_comboBox.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_comboBox.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_comboBox.setLineWidth(3)
        self.frame_comboBox.setObjectName("frame_comboBox")
        self.verticalLayout.addWidget(self.frame_comboBox)

        self.gridLayout_comboBox = QtWidgets.QGridLayout(self.frame_comboBox)
        self.gridLayout_comboBox.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_comboBox.setObjectName("gridLayout_optionalstock222")

        self.gridLayout_comboBox.addWidget(self.comboBox_kline, 4, 0, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_exchange, 4, 1, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_instrument, 4, 2, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_instrumentid, 4, 3, 1, 1)

        # K线图位置
        # global logYdata
        self.item = CandlestickItem(data_kline)  # 原始数据,对应（0,0）幅图
        npdata = np.array(data_kline)
        # logYdata = np.log(npdata[:, 1:])
        # self.logYdata = np.log(npdata[1:, 2:])
        # self.logYdata = np.insert(self.logYdata, 0, values=npdata[:, 0], axis=1)
        # self.logYdata = list(map(tuple, self.logYdata))
        self.wkline = pg.GraphicsWindow()
        self.wkline.setWindowTitle('pyqtgraph example: customGraphicsItem')

        self.plt_kline = self.wkline.addPlot(1, 1, title="K线图")

        self.plt_kline.addItem(self.item)
        self.plt_kline.showGrid(True, True)
        self.plt_kline.setMouseEnabled(x=True, y=True)  # 禁用轴操作
        self.verticalLayout.addWidget(self.wkline)
        self.wkline.showMaximized()
        # K线图位置

        # 分时图
        self.winmarket = pg.GraphicsLayoutWidget(show=True)
        self.winmarket.setWindowTitle('闪电图')
        self.plt_market = self.winmarket.addPlot(title="闪电图")
        # plt_market.setAutoVisibleOnly(y=True)
        self.curve_market = self.plt_market.plot()
        self.plt_market.setMouseEnabled(x=False, y=False)  # 禁用轴操作
        self.verticalLayout.addWidget(self.winmarket)
        self.winmarket.showMaximized()
        # 分时图

        # Tab1 实时资金曲线位置
        self.win = pg.GraphicsLayoutWidget(show=True)
        self.win.setWindowTitle('实时资金曲线(10秒取样1次)')
        self.plt_realtime = self.win.addPlot(title="实时资金曲线(10秒取样1次)")
        # self.win.setBackground('y')
        # plt_realtime.setAutoVisibleOnly(y=True)
        self.curve_realtime = self.plt_realtime.plot(pen='y')
        self.plt_realtime.setMouseEnabled(x=False, y=False)  # 禁用轴操作
        self.verticalLayout.addWidget(self.win)
        self.win.showMaximized()
        # Tab1 实时资金曲线位置

        # 进度条
        self.progressBar = QtWidgets.QProgressBar(self.dockWidgetContents)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setFormat("仓位：%p%")
        self.progressBar.setObjectName("总仓位")
        self.verticalLayout.addWidget(self.progressBar)
        # 决定绘图多窗口
        self.verticalLayout_2.addLayout(self.verticalLayout)

        self.Button_h = []

        self.temps = QtWidgets.QPushButton('最近访问1')
        self.temps.setObjectName("Button_h1")
        self.temps.clicked.connect(self.Function_Buttonclickh1)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问2')
        self.temps.setObjectName("Button_h2")
        self.temps.clicked.connect(self.Function_Buttonclickh2)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问3')
        self.temps.setObjectName("Button_h3")
        self.temps.clicked.connect(self.Function_Buttonclickh3)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问4')
        self.temps.setObjectName("Button_h4")
        self.temps.clicked.connect(self.Function_Buttonclickh4)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问5')
        self.temps.setObjectName("Button_h5")
        self.temps.clicked.connect(self.Function_Buttonclickh5)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问6')
        self.temps.setObjectName("Button_h6")
        self.temps.clicked.connect(self.Function_Buttonclickh6)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问7')
        self.temps.setObjectName("Button_h7")
        self.temps.clicked.connect(self.Function_Buttonclickh7)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问8')
        self.temps.setObjectName("Button_h8")
        self.temps.clicked.connect(self.Function_Buttonclickh8)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问9')
        self.temps.setObjectName("Button_h9")
        self.temps.clicked.connect(self.Function_Buttonclickh9)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问10')
        self.temps.setObjectName("Button_h10")
        self.temps.clicked.connect(self.Function_Buttonclickh10)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问11')
        self.temps.setObjectName("Button_h11")
        self.temps.clicked.connect(self.Function_Buttonclickh11)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问12')
        self.temps.setObjectName("Button_h12")
        self.temps.clicked.connect(self.Function_Buttonclickh12)
        self.Button_h.append(self.temps)

        self.Button_t = []

        self.temps = QtWidgets.QPushButton('最近交易1')
        self.temps.setObjectName("Button_t1")
        self.temps.clicked.connect(self.Function_Buttonclickt1)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易2')
        self.temps.setObjectName("Button_t2")
        self.temps.clicked.connect(self.Function_Buttonclickt2)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易3')
        self.temps.setObjectName("Button_t3")
        self.temps.clicked.connect(self.Function_Buttonclickt3)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易4')
        self.temps.setObjectName("Button_t4")
        self.temps.clicked.connect(self.Function_Buttonclickt4)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易5')
        self.temps.setObjectName("Button_t5")
        self.temps.clicked.connect(self.Function_Buttonclickt5)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易6')
        self.temps.setObjectName("Button_t6")
        self.temps.clicked.connect(self.Function_Buttonclickt6)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易7')
        self.temps.setObjectName("Button_t7")
        self.temps.clicked.connect(self.Function_Buttonclickt7)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易8')
        self.temps.setObjectName("Button_t8")
        self.temps.clicked.connect(self.Function_Buttonclickt8)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易9')
        self.temps.setObjectName("Button_t9")
        self.temps.clicked.connect(self.Function_Buttonclickt9)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易10')
        self.temps.setObjectName("Button_t10")
        self.temps.clicked.connect(self.Function_Buttonclickt10)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易11')
        self.temps.setObjectName("Button_t11")
        self.temps.clicked.connect(self.Function_Buttonclickt11)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易12')
        self.temps.setObjectName("Button_t12")
        self.temps.clicked.connect(self.Function_Buttonclickt12)
        self.Button_t.append(self.temps)

        self.Button_zx = []

        self.temps = QtWidgets.QPushButton('自选1')
        self.temps.setObjectName("Button_zx1")
        self.temps.clicked.connect(self.Function_Buttonclickz1)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选2')
        self.temps.setObjectName("Button_zx2")
        self.temps.clicked.connect(self.Function_Buttonclickz2)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选3')
        self.temps.setObjectName("Button_zx3")
        self.temps.clicked.connect(self.Function_Buttonclickz3)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选4')
        self.temps.setObjectName("Button_zx4")
        self.temps.clicked.connect(self.Function_Buttonclickz4)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选5')
        self.temps.setObjectName("Button_zx5")
        self.temps.clicked.connect(self.Function_Buttonclickz5)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选6')
        self.temps.setObjectName("Button_zx6")
        self.temps.clicked.connect(self.Function_Buttonclickz6)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选7')
        self.temps.setObjectName("Button_zx7")
        self.temps.clicked.connect(self.Function_Buttonclickz7)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选8')
        self.temps.setObjectName("Button_zx8")
        self.temps.clicked.connect(self.Function_Buttonclickz8)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选9')
        self.temps.setObjectName("Button_zx9")
        self.temps.clicked.connect(self.Function_Buttonclickz9)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选10')
        self.temps.setObjectName("Button_zx10")
        self.temps.clicked.connect(self.Function_Buttonclickz10)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选11')
        self.temps.setObjectName("Button_zx11")
        self.temps.clicked.connect(self.Function_Buttonclickz11)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选12')
        self.temps.setObjectName("Button_zx12")
        self.temps.clicked.connect(self.Function_Buttonclickz12)
        self.Button_zx.append(self.temps)

        self.Button_e0 = QtWidgets.QPushButton('Talib指标条件设置(升级中)')
        self.Button_e0.setObjectName("Button_e0")
        self.Button_e0.clicked.connect(self.Function_Buttonclicke0)

        self.Button_e1 = QtWidgets.QPushButton('自定义指标(升级中)')
        self.Button_e1.setObjectName("Button_e1")
        self.Button_e1.clicked.connect(self.Function_Buttonclicke1)

        self.Button_e2 = QtWidgets.QPushButton('指标条件组合策略(升级中)')
        self.Button_e2.setObjectName("Button_e2")
        self.Button_e2.clicked.connect(self.Function_Buttonclicke2)

        self.Button_e3 = QtWidgets.QPushButton('随机组合生成(升级中)')
        self.Button_e3.setObjectName("Button_e3")
        self.Button_e3.clicked.connect(self.Function_Buttonclicke3)

        self.Button_e4 = QtWidgets.QPushButton('指标自动交易合约选择(升级中)')
        self.Button_e4.setObjectName("Button_e4")
        self.Button_e4.clicked.connect(self.Function_Buttonclicke4)

        self.Button_e5 = QtWidgets.QPushButton('数据统计(升级中)')
        self.Button_e5.setObjectName("Button_e5")
        self.Button_e5.clicked.connect(self.Function_Buttonclicke5)

        self.frame = QtWidgets.QFrame(self.Button_h[0])
        self.frame.setMinimumSize(QtCore.QSize(0, 0))
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setLineWidth(3)
        self.frame.setObjectName("frame")
        self.verticalLayout.addWidget(self.frame)

        self.gridLayout_optionalstock = QtWidgets.QGridLayout(self.frame)
        self.gridLayout_optionalstock.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_optionalstock.setObjectName("gridLayout_optionalstock")
        self.gridLayout_optionalstock.addWidget(self.Button_h[0], 1, 0, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[1], 1, 1, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[2], 1, 2, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[3], 1, 3, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[4], 1, 4, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[5], 1, 5, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[6], 1, 6, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[7], 1, 7, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[8], 1, 8, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[9], 1, 9, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[10], 1, 10, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[11], 1, 11, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[0], 2, 0, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[1], 2, 1, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[2], 2, 2, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[3], 2, 3, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[4], 2, 4, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[5], 2, 5, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[6], 2, 6, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[7], 2, 7, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[8], 2, 8, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[9], 2, 9, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[10], 2, 10, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[11], 2, 11, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[0], 3, 0, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[1], 3, 1, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[2], 3, 2, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[3], 3, 3, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[4], 3, 4, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[5], 3, 5, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[6], 3, 6, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[7], 3, 7, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[8], 3, 8, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[9], 3, 9, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[10], 3, 10, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[11], 3, 11, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_e0, 4, 0, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e1, 4, 2, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e2, 4, 4, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e3, 4, 6, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e4, 4, 8, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e5, 4, 10, 1, 2)

        geo = self.Button_h[0].geometry()
        geo.moveCenter(self.frame.rect().center())

        self.verticalLayout_2.addWidget(self.frame)
        self.dockWidget1.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget1)
        self.toolBar = QtWidgets.QToolBar(MainWindow)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.dockWidget2 = QtWidgets.QDockWidget(MainWindow)
        self.dockWidget2.setObjectName("dockWidget2")
        self.dockWidgetContents_2 = QtWidgets.QWidget()
        self.dockWidgetContents_2.setObjectName("dockWidgetContents_2")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.dockWidgetContents_2)
        self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_3.setObjectName("gridLayout_3")
        # 左边行情滚动位置

        self.dockWidget2.setWidget(self.dockWidgetContents_2)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget2)

        # 热力图
        '''
        self.gr_wid = pg.GraphicsLayoutWidget(show=True)
        ## Create image items
        data4 = np.fromfunction(lambda i, j: (1 + 0.3 * np.sin(i)) * (i) ** 2 + (j) ** 2, (100, 100))
        noisy_data = data4 * (1 + 0.2 * np.random.random(data4.shape))
        noisy_transposed = noisy_data.transpose()

        # --- add non-interactive image with integrated color -----------------
        i1 = pg.ImageItem(image=data4)
        p1 = self.gr_wid.addPlot(title="参数优化")
        p1.addItem(i1)
        p1.setMouseEnabled(x=False, y=False)
        p1.disableAutoRange()
        # p1.hideButtons()
        p1.setRange(xRange=(0, 100), yRange=(0, 100), padding=0)
        for key in ['left', 'right', 'top', 'bottom']:
            p1.showAxis(key)
            axis = p1.getAxis(key)
            axis.setZValue(1)
            if key in ['top', 'right']:
                p1.getAxis(key).setStyle(showValues=False)

        cmap = pg.colormap.get('CET-L9')
        bar = pg.ColorBarItem(
            interactive=False, values=(0, 30_000), cmap=cmap,
            label='vertical fixed color bar'
        )
        bar.setImageItem(i1, insert_in=p1)

        # manually adjust reserved space at top and bottom to align with plot
        bar.getAxis('bottom').setHeight(21)
        bar.getAxis('top').setHeight(31)
        self.gr_wid.addItem(bar, 0, 2, 2, 1)  # large bar spanning both rows

        # self.verticalLayout.addWidget(self.gr_wid)
        self.gridLayout_3.addWidget(self.gr_wid, 0, 0, 1, 1)
        # self.win.showMaximized()
        '''
        # 热力图

        # TAB2 回测资金曲线位置
        self.win5 = pg.GraphicsLayoutWidget(show=True)
        self.win5.setWindowTitle('资金曲线')
        self.plt_backtest = self.win5.addPlot(title="资金曲线")
        # self.win.setBackground('y')
        # plt_backtesting.setAutoVisibleOnly(y=True)
        self.curve_backtest = self.plt_backtest.plot(pen='y')
        self.plt_backtest.setMouseEnabled(x=False, y=False)  # 禁用轴操作
        self.gridLayout_3.addWidget(self.win5, 1, 0, 1, 1)
        self.win5.showMaximized()
        # TAB2 回测资金曲线位置

        self.Button_OpenDll = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_OpenDll.setObjectName("Button_OpenDll")
        self.Button_CloseDll = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_CloseDll.setObjectName("Button_CloseDll")
        self.Button_StrategyManage_SingleThread = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_StrategyManage_SingleThread.setObjectName("Button_StrategyManage_SingleThread")
        self.Button_StrategyManage_MulitProcess = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_StrategyManage_MulitProcess.setObjectName("Button_StrategyManage_MulitProcess")
        self.Button_KlineSource_RealTimeTick = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_RealTimeTick.setObjectName("Button_KlineSource_RealTimeTick")
        self.Button_KlineSource_ServerToday = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_ServerToday.setObjectName("Button_KlineSource_ServerToday")
        self.Button_KlineSource_ServerMultiday = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_ServerMultiday.setObjectName("Button_KlineSource_ServerMultiday")
        self.Button_CloseDll.setChecked(True)
        self.Button_StrategyManage_SingleThread.setChecked(True)
        # self.Button_KlineSource_RealTimeTick.setChecked(True)

        self.Navgiate1 = QtWidgets.QAction(MainWindow)
        self.Navgiate1.setObjectName("Navgiate1")
        self.Navgiate2 = QtWidgets.QAction(MainWindow)
        self.Navgiate2.setObjectName("Navgiate2")
        self.Navgiate3 = QtWidgets.QAction(MainWindow)
        self.Navgiate3.setObjectName("Navgiate3")
        self.Navgiate4 = QtWidgets.QAction(MainWindow)
        self.Navgiate4.setObjectName("Navgiate4")
        self.Navgiate5 = QtWidgets.QAction(MainWindow)
        self.Navgiate5.setObjectName("Navgiate5")
        self.Navgiate6 = QtWidgets.QAction(MainWindow)
        self.Navgiate6.setObjectName("Navgiate6")
        self.Navgiate7 = QtWidgets.QAction(MainWindow)
        self.Navgiate7.setObjectName("Navgiate7")
        self.Navgiate8 = QtWidgets.QAction(MainWindow)
        self.Navgiate8.setObjectName("Navgiate8")
        self.Navgiate1_C = QtWidgets.QAction(MainWindow)
        self.Navgiate1_C.setObjectName("Navgiate1_C")
        self.menuSubmenu_2.addAction(self.Navgiate2)
        self.menuSubmenu_2.addAction(self.Navgiate1_C)
        self.menuMenu_nav1.addAction(self.Button_OpenDll)
        self.menuMenu_nav1.addAction(self.Button_CloseDll)

        self.menuMenu_nav2.addAction(self.Button_StrategyManage_SingleThread)
        self.menuMenu_nav2.addAction(self.Button_StrategyManage_MulitProcess)

        self.menuMenu_nav3.addAction(self.Button_KlineSource_RealTimeTick)
        self.menuMenu_nav3.addAction(self.Button_KlineSource_ServerToday)
        self.menuMenu_nav3.addAction(self.Button_KlineSource_ServerMultiday)

        # self.menuMenu.addAction(self.menuSubmenu_2.menuAction())
        self.menubar.addAction(self.menuMenu_nav1.menuAction())
        self.menubar.addAction(self.menuMenu_nav2.menuAction())
        self.menubar.addAction(self.menuMenu_nav3.menuAction())

        # self.menuMenu.addAction(self.Navgiate1)
        # self.menuMenu.addAction(self.menuSubmenu_2.menuAction())
        # self.menubar.addAction(self.menuMenu.menuAction())

        self.toolBar.addAction(self.Navgiate1)
        self.toolBar.addAction(self.Navgiate2)
        self.toolBar.addAction(self.Navgiate3)
        self.toolBar.addAction(self.Navgiate4)
        self.toolBar.addAction(self.Navgiate5)
        self.toolBar.addAction(self.Navgiate6)
        self.toolBar.addAction(self.Navgiate7)
        self.toolBar.addAction(self.Navgiate8)
        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        self.toolBox1.setCurrentIndex(1)
        self.toolBox2.setCurrentIndex(1)
        self.tabWidget_2.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        # MainWindow.setTabOrder(self.pushButton, self.checkableButton)
        # MainWindow.setTabOrder(self.checkableButton, self.pushButton_5)
        # MainWindow.setTabOrder(self.pushButton_5, self.tabWidget_2)
        MainWindow.setTabOrder(self.tabWidget_2, self.table_account)
        # MainWindow.setTabOrder(self.tabWidget, self.table_strategy)
        MainWindow.setTabOrder(self.table_account, self.radioButton)
        MainWindow.setTabOrder(self.radioButton, self.checkBox)
        MainWindow.setTabOrder(self.checkBox, self.checkBox_2)
        MainWindow.setTabOrder(self.checkBox_2, self.treeWidget)
        MainWindow.setTabOrder(self.treeWidget, self.Button_Start)
        # MainWindow.setTabOrder(self.Button_Start, self.menu_a_popup)
        # MainWindow.setTabOrder(self.menu_a_popup, self.menu_b_popup)
        # MainWindow.setTabOrder(self.menu_b_popup, self.menu_c_popup)
        # MainWindow.setTabOrder(self.menu_c_popup, self.Button_Stop)
        # MainWindow.setTabOrder(self.Button_Stop, self.doubleSpinBox)
        # MainWindow.setTabOrder(self.doubleSpinBox, self.toolButton)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_kline)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_exchange)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_instrument)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_instrumentid)

        # 左边行情滚动位置
        # MainWindow.setTabOrder(self.comboBox, self.horizontalSlider)
        # MainWindow.setTabOrder(self.horizontalSlider, self.textEdit)
        # 左边行情滚动位置
        # MainWindow.setTabOrder(self.textEdit, self.verticalSlider)
        # MainWindow.setTabOrder(self.verticalSlider, self.tabWidget)

        # 1，1 委托记录
        # MainWindow.setTabOrder(self.tabWidget, self.lineEdit)
        # MainWindow.setTabOrder(self.lineEdit, self.listWidget)

    # 更新回测资金曲线
    def updatebacktestingUi(self, newdata):
        def update_backtesting(newdata):
            global data_backtesting, count
            data_backtesting.append(newdata)
            if len(data_backtesting) > 100:
                data_backtesting.pop(0)
            self.curve_backtesting.setData(np.hstack(data_backtesting))
            count += 1

        for i in range(101):
            update_backtesting(newdata)

    # 从文件读取更新当日K线图
    def UpdateKlineUIFromFile(self, InstrumentID, TradingDay):
        try:
            global kid, count
            kid = 1
            fname = globalvar.currpath + "\\data_today\\" + InstrumentID + ".csv"
            print('filename: ' + fname)
            globalvar.ticklist = []
            if os.path.isfile(fname):
                for line in open(fname):
                    QApplication.processEvents()
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            int(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': int(ld[7]),
                    }, ignore_index=True)
                    kid = kid + 1
            self.plt_kline.removeItem(self.item)

            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
                count += 1
            except Exception as e:
                print("UpdateKlineUIFromFileB Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])

            # 根据M1周期K线合成M3周期K线数据
            # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")
        except Exception as e:
            print("UpdateKlineUIFromFile Error:" + repr(e))

    def UpdateKlineUIFromFileBakUp(self, InstrumentID, TradingDay):
        try:
            global kid, count
            kid = 1
            fname = globalvar.currpath + "\\data_today\\" + InstrumentID + ".csv"
            print('filename: ' + fname)
            globalvar.ticklist = []
            if os.path.isfile(fname):
                for line in open(fname):
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            int(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': int(ld[7]),
                    }, ignore_index=True)
                    kid = kid + 1
            self.plt_kline.removeItem(self.item)

            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
                count += 1
            except Exception as e:
                print("UpdateKlineUIFromFileB Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])

            # 根据M1周期K线合成M3周期K线数据
            # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")


        except Exception as e:
            print("UpdateKlineUIFromFile Error:" + repr(e))

    def dateprevious(self, year, mouth, day):
        list_mouth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if day == 1:
            if mouth == 1:
                year = year - 1
                mouth = 12
                day = list_mouth[mouth - 1]
            else:
                mouth = mouth - 1
                day = list_mouth[mouth - 1]
                if day == 28:
                    if year % 4 == 0:
                        day = 29
        else:
            day = day - 1
        return year * 10000 + mouth * 100 + day

    # 从文件读取更新多日M1 K线图
    def UpdateMultiKlineUIFromFile(self, InstrumentID, TradingDay):
        global kid
        kid = 1
        TradingDaylist = []
        globalvar.ticklist = []
        newTradingDay = TradingDay
        for addday in range(10):
            tyear = int(str(newTradingDay)[0:4])
            tmonth = int(str(newTradingDay)[4:6])
            tday = int(str(newTradingDay)[6:8])
            newTradingDay = self.dateprevious(tyear, tmonth, tday)
            TradingDaylist.append(newTradingDay)
        TradingDaylist.reverse()
        for addday in range(10):
            fname = globalvar.currpath + "\\data_multiday\\" + InstrumentID + "\\" + str(
                TradingDaylist[addday]) + ".csv"
            if os.path.isfile(fname):
                for line in open(fname):
                    QApplication.processEvents()
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            int(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        # 'recordid': ld[0] + str(kid),
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': int(ld[7]),
                    }, ignore_index=True)

                    kid = kid + 1
        fname = globalvar.currpath + "\\data_multiday\\" + InstrumentID + "\\" + str(TradingDay) + ".csv"

        if os.path.isfile(fname):
            for line in open(fname):
                QApplication.processEvents()
                ld = line.split(',')
                temp = (kid,
                        float(ld[0]),
                        float(ld[1]),
                        float(ld[3]),
                        float(ld[4]),
                        float(ld[5]),
                        int(ld[6]))
                globalvar.data_kline_M1.append(temp)

                tempstr = str(int(float(ld[1]) * 10000))
                tempstr_list = list(tempstr)
                tempstr_list.insert(len(tempstr_list) - 2, ':')
                tempstr = ''.join(tempstr_list)

                globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                '''
                globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                    {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                     'vol': []}, index=[])
                '''

                ld[1] = ld[1].ljust(8, '0')
                ld[1] = '{:0>8s}'.format(ld[1])
                tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                        4:6] + ":" + ld[
                                                                                                                         1][
                                                                                                                     6:8]
                globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                    InstrumentID].append({
                    'datetime': tdatetime,
                    'recordid': '{:0>8s}'.format(str(kid)),
                    'tradingday': ld[0],
                    'klinetime': ld[1],
                    'instrumentid': ld[2],
                    'open': float(ld[3]),
                    'close': float(ld[4]),
                    'low': float(ld[5]),
                    'high': float(ld[6]),
                    'vol': int(ld[7]),
                }, ignore_index=True)

                kid = kid + 1
        self.plt_kline.removeItem(self.item)
        self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
        # npdata = np.array(globalvar.data_kline_M1)
        try:
            self.plt_kline.addItem(self.item)
            count += 1
        except Exception as e:
            print("UpdateMultiKlineUIFromFile Error:" + repr(e))
        # globalvar.dict_data_kline_M1[InstrumentID] = globalvar.data_kline_M1.copy()

        # 横坐标刻度
        xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
        xdict = dict(enumerate(globalvar.ticklist))
        xax.setTicks([xdict.items()])

        # 根据M1周期K线合成M3周期K线数据
        # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")

    # 更新K线图
    def updateklineUi(self, InstrumentID):
        if globalvar.md:
            try:
                global lasttime
                global kid, count
                kid = kid + 1
                if lasttime != globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime:
                    lasttime = globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime
                    thiskid = globalvar.data_kline_M1[len(globalvar.data_kline_M1) - 1][0] + 1
                    temp = (
                        thiskid,
                        float(globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay.decode('utf-8')),
                        globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime,
                        globalvar.md.GetKline(InstrumentID, 1).contents.Open,
                        globalvar.md.GetKline(InstrumentID, 1).contents.Close,
                        globalvar.md.GetKline(InstrumentID, 1).contents.Low,
                        globalvar.md.GetKline(InstrumentID, 1).contents.High
                        # globalvar.md.GetKline(InstrumentID, 1).contents.Volume
                    )

                    globalvar.data_kline_M1.append(temp)
                    # tempstr = str(int(float(globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay) * 10000))
                    tempstr = str(int(float(globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay)))
                    tempstr_list = list(tempstr)
                    # tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    klinetimestr = str(globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime)
                    globalvar.ticklist.append(tempstr + "\n" + klinetimestr)
                    TradingDay = str(globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay,
                                     encoding="utf-8").ljust(8, '0')
                    TradingDay = '{:0>8s}'.format(TradingDay)
                    tdatetime = klinetimestr[0:4] + "-" + klinetimestr[4:6] + "-" + klinetimestr[
                                                                                    6:8] + " " + TradingDay[
                                                                                                 2:4] + ":" + TradingDay[
                                                                                                              4:6] + ":" + TradingDay[
                                                                                                                           6:8]
                    try:
                        if globalvar.notfirstupdateklineUi:
                            InstrumentID_key = InstrumentID.decode('utf-8')
                            globalvar.dict_dataframe_kline_M1[InstrumentID_key] = globalvar.dict_dataframe_kline_M1[
                                InstrumentID_key].append({
                                'datetime': tdatetime,
                                'recordid': '{:0>8s}'.format(str(thiskid)),
                                'tradingday': float(
                                    globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay.decode('utf-8')),
                                'klinetime': klinetimestr,
                                'instrumentid': InstrumentID,
                                'open': globalvar.md.GetKline(InstrumentID, 1).contents.Open,
                                'close': globalvar.md.GetKline(InstrumentID, 1).contents.Close,
                                'low': globalvar.md.GetKline(InstrumentID, 1).contents.Low,
                                'high': globalvar.md.GetKline(InstrumentID, 1).contents.High,
                                'vol': globalvar.md.GetKline(InstrumentID, 1).contents.Volume,
                            }, ignore_index=True)
                            self.plt_kline.removeItem(self.item)
                            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
                        else:
                            globalvar.notfirstupdateklineUi = True
                    except Exception as e: \
                            print("dict_dataframe_kline_M1 No Key:" + repr(e))

                    try:
                        self.plt_kline.addItem(self.item)
                        count += 1
                    except Exception as e:
                        print("UpdateKlineUIFromFileB Error:" + repr(e))
                    # 横坐标刻度
                    xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
                    xdict = dict(enumerate(globalvar.ticklist))
                    xax.setTicks([xdict.items()])
                    # 根据M1周期K线合成M3周期K线数据
                    # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")
            except Exception as e:
                print("updateklineUi Error:" + repr(e))

    # 更新分时图
    def updatemarketUi(self, newdata):
        def update_market(newdata):
            global data_market, count
            data_market.append(newdata)
            if len(data_market) > 1000:
                data_market.pop(0)
            self.curve_market.setData(np.hstack(data_market))
            count += 1

        update_market(newdata)

    global lastTradingDay
    lastTradingDay = ''

    # 更新实时资金曲线
    def updaterealtimecurveUi(self, newdata, TradingDay):
        def update_realtime(newdata):
            global data_realtimecurve, count, lastTradingDay
            data_realtimecurve.append(newdata)
            # if len(data_realtimecurve) > 100:
            if TradingDay != lastTradingDay:
                lastTradingDay = TradingDay
                data_realtimecurve.pop(0)
            else:
                self.curve_realtime.setData(np.hstack(data_realtimecurve))
            count += 1

        update_realtime(newdata)

    def fileTime(self, file):
        return [time.ctime(os.path.getatime(file)), time.ctime(os.path.getctime(file)),
                time.ctime(os.path.getmtime(file))]

    # 单线程由Python直接驱动策略, 支持文件类型：（1）.py
    def Function_delete_clicked(self, arg):
        button = self.MainWindow.sender()
        if button:
            row = self.table_strategy.indexAt(button.pos()).row()
            self.table_strategy.removeRow(row)

    # 策略管理器模式
    def Function_ScanStrategy(self):
        if True:
            module_strategy.Function_ScanStrategy_SingleThreadPyManage()
        else:
            module_strategy.Function_ScanStrategy_MulitProcess()

    # 扫描合约组设置
    def Function_ScanInstrumentIDGroup(self):
        module_instrumentgroup.Function_ScanInstrumentIDGroup()

    def Function_ScanMDHistorylog(self):
        path = "logfile/md"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".txt":

                    if c_path in module_strategy.dict_strategy:
                        if module_strategy.dict_strategy[c_path] != self.fileTime(c_path):
                            print("修改了")
                    else:
                        '''
                        filenameini = c_path
                        filenameini=filenameini.replace('py','ini')
                        #  实例化configParser对象
                        config = configparser.ConfigParser()
                        # -read读取ini文件
                        config.read(filenameini,encoding='utf-8')
                        if config.getint('setting', 'run')==1:
                            module_strategy.dict_strategyrun[c_path] = 1
                        else:
                            module_strategy.dict_strategyrun[c_path] = 0
                        '''
                        module_strategy.dict_strategy[c_path] = self.fileTime(c_path)
                        # print("find Strategy file:", c_path,self.fileTime(c_path))
                        row_cnt = self.table_historymd.rowCount()  # 返回当前行数（尾部）
                        # print("列数：",row_cnt)
                        self.table_historymd.insertRow(row_cnt)  # 尾部插入一行新行表格
                        column_cnt = self.table_historymd.columnCount()  # 返回当前列数
                        # for column in range(column_cnt):
                        item = QTableWidgetItem(str(row_cnt + 1))

                        # if module_strategy.run[c_path] == 1:
                        #    item.setCheckState(QtCore.Qt.Checked)
                        # else:
                        #    item.setCheckState(QtCore.Qt.Unchecked)

                        self.table_historymd.setItem(row_cnt, 0, item)
                        item = QTableWidgetItem(str(c_path))
                        self.table_historymd.setItem(row_cnt, 1, item)
                        # item2 = QtWidgets.QTableWidgetItem("1")
                        # item.setCheckState(QtCore.Qt.Unchecked)
                        # self.table_historymd.setItem(0, 0, item2)

    def Function_ScanTDHistorylog(self):
        path = "logfile/td"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".txt":

                    if c_path in module_strategy.dict_strategy:
                        if module_strategy.dict_strategy[c_path] != self.fileTime(c_path):
                            print("修改了")
                    else:
                        '''
                        filenameini = c_path
                        filenameini=filenameini.replace('py','ini')
                        #  实例化configParser对象
                        config = configparser.ConfigParser()
                        # -read读取ini文件
                        config.read(filenameini,encoding='utf-8')
                        if config.getint('setting', 'run')==1:
                            module_strategy.dict_strategyrun[c_path] = 1
                        else:
                            module_strategy.dict_strategyrun[c_path] = 0
                        '''
                        module_strategy.dict_strategy[c_path] = self.fileTime(c_path)
                        # print("find Strategy file:", c_path,self.fileTime(c_path))
                        row_cnt = self.table_historytd.rowCount()  # 返回当前行数（尾部）
                        # print("列数：",row_cnt)
                        self.table_historytd.insertRow(row_cnt)  # 尾部插入一行新行表格
                        column_cnt = self.table_historytd.columnCount()  # 返回当前列数
                        # for column in range(column_cnt):
                        item = QTableWidgetItem(str(row_cnt + 1))
                        # if module_strategy.dict_strategyrun[c_path] == 1:
                        #    item.setCheckState(QtCore.Qt.Checked)
                        # else:
                        #    item.setCheckState(QtCore.Qt.Unchecked)
                        self.table_historytd.setItem(row_cnt, 0, item)
                        item = QTableWidgetItem(str(c_path))
                        self.table_historytd.setItem(row_cnt, 1, item)
                        # item2 = QtWidgets.QTableWidgetItem("1")
                        # item.setCheckState(QtCore.Qt.Unchecked)
                        # self.table_historytd.setItem(0, 0, item2)

    # 打开策略目录
    def Function_OpenStrategyPath(self):
        cur_dir = QDir.currentPath() + "/strategyfile"
        os.startfile(cur_dir)

    # 打开回测报告目录
    def Function_OpenBackTestingPath(self):
        cur_dir = QDir.currentPath() + "/backtesting"
        os.startfile(cur_dir)

    # 清空今日行情日志
    def Function_ClearTodayMdLog(self):
        # self.ClearPath("log/md")
        self.list_listmdlog.clear()
        pass

    # 清空今日交易日志
    def Function_ClearTodayTdLog(self):
        # self.ClearPath("log/md")
        self.list_listtdlog.clear()
        pass

    # 打开算法交易目录
    def Function_OpenAlgorithmicTradingPath(self):
        cur_dir = QDir.currentPath() + "/AlgorithmicTrading"
        os.startfile(cur_dir)

    # 扫描交易历史日志
    def Function_ScanTdLog(self):
        path = "log"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".py" or type == ".pyd" or type == ".pyc":
                    print("find log file:", c_path)
                    # item = QtWidgets.table_strategy()
                    # self.table_strategy.setVerticalHeaderItem(1, item)

    # 扫描行情历史日志
    def Function_ScanMdLog(self):
        path = "log"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".py" or type == ".pyd" or type == ".pyc":
                    print("find log file:", c_path)
                    # item = QtWidgets.table_strategy()
                    # self.table_strategy.setVerticalHeaderItem(1, item)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        # 交易信息
        self.groupBox.setTitle(_translate("MainWindow", ""))
        self.toolBox1.setItemText(self.toolBox1.indexOf(self.page_order), _translate("MainWindow", "委托记录"))
        self.toolBox2.setItemText(self.toolBox2.indexOf(self.page_instrument), _translate("MainWindow", "合约参数"))
        self.toolBox1.setItemText(self.toolBox1.indexOf(self.page_trade), _translate("MainWindow", "交易记录"))
        self.toolBox2.setItemText(self.toolBox2.indexOf(self.page_position), _translate("MainWindow", "全部持仓/策略持仓"))
        # self.checkableButton.setText(_translate("MainWindow", "Checkable button"))
        # self.pushButton.setText(_translate("MainWindow", "PushButton"))
        # self.pushButton_5.setText(_translate("MainWindow", "PushButton"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_strategy), _translate("MainWindow", "策略"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_instrumentgroup), _translate("MainWindow", "合约组"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_account), _translate("MainWindow", "账号"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_plus), _translate("MainWindow", "增值服务"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_algorithmtrading),
                                    _translate("MainWindow", "算法交易"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_instrument), _translate("MainWindow", "合约参数"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_marketdata), _translate("MainWindow", "Tick"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_listtdlog), _translate("MainWindow", "交易日志"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_listmdlog), _translate("MainWindow", "行情日志"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_historytd), _translate("MainWindow", "历史交易"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_historymd), _translate("MainWindow", "历史行情"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_backtestdata), _translate("MainWindow", "回测数据"))
        # self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_report), _translate("MainWindow", "回测报告"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_result), _translate("MainWindow", "回测报告"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_faq), _translate("MainWindow", "FAQ"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "交易主界面"))
        self.groupBox_2.setTitle(_translate("MainWindow", "GroupBox"))
        self.label.setText(_translate("MainWindow", "TextLabel"))
        self.radioButton.setText(_translate("MainWindow", "RadioB&utton"))
        self.checkBox.setText(_translate("MainWindow", "CheckBox"))
        self.checkBox_2.setText(_translate("MainWindow", "CheckBox Tristate"))
        self.treeWidget.headerItem().setText(8, _translate("MainWindow", "qdz"))
        __sortingEnabled = self.treeWidget.isSortingEnabled()
        self.treeWidget.setSortingEnabled(False)
        self.treeWidget.topLevelItem(0).setText(0, _translate("MainWindow", "qzd"))
        self.treeWidget.topLevelItem(1).setText(0, _translate("MainWindow", "effefe"))
        self.treeWidget.setSortingEnabled(__sortingEnabled)
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "选项设置"))
        # self.Button_Start.setText(_translate("MainWindow", ""))
        # self.Button_Stop.setText(_translate("MainWindow", ""))
        # self.menu_a_popup.setText(_translate("MainWindow", "menu_a_popup"))
        self.menu_b_popup.setText(_translate("MainWindow", "交易功能项"))
        # self.menu_c_popup.setText(_translate("MainWindow", "menu_c_popup"))
        self.toolButton.setText(_translate("MainWindow", "..."))
        self.menuMenu_nav1.setTitle(_translate("MainWindow", "&底层Dll日志"))
        self.menuMenu_nav2.setTitle(_translate("MainWindow", "&策略管理器"))
        self.menuMenu_nav3.setTitle(_translate("MainWindow", "&K线数据来源"))
        self.menuSubmenu_2.setTitle(_translate("MainWindow", "&Submenu 2"))
        # self.dockWidget1.setWindowTitle(_translate("MainWindow", "&Dock widget 1"))
        self.dockWidget1.setWindowTitle(_translate("MainWindow", "实时行情和资金曲线(根据Tick实时生成K线)"))
        self.dockWidget1.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.comboBox_kline.setItemText(0, _translate("MainWindow", "K线周期: M1"))
        self.comboBox_kline.setItemText(1, _translate("MainWindow", "K线周期: M3"))
        self.comboBox_kline.setItemText(2, _translate("MainWindow", "K线周期: M5"))
        self.comboBox_kline.setItemText(3, _translate("MainWindow", "K线周期: M10"))
        self.comboBox_kline.setItemText(4, _translate("MainWindow", "K线周期: M15"))
        self.comboBox_kline.setItemText(5, _translate("MainWindow", "K线周期: M30"))
        self.comboBox_kline.setItemText(6, _translate("MainWindow", "K线周期: M60"))
        self.comboBox_kline.setItemText(7, _translate("MainWindow", "K线周期: D1"))
        self.comboBox_exchange.setItemText(0, _translate("MainWindow", "ALL,全部交易所"))
        self.comboBox_exchange.setItemText(1, _translate("MainWindow", "SHFE,上期所"))
        self.comboBox_exchange.setItemText(2, _translate("MainWindow", "DCE,大商所"))
        self.comboBox_exchange.setItemText(3, _translate("MainWindow", "CZCE,郑商所"))
        self.comboBox_exchange.setItemText(4, _translate("MainWindow", "CFFEX,中金所"))
        self.comboBox_exchange.setItemText(5, _translate("MainWindow", "INE,能源所"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
        self.dockWidget2.setWindowTitle(_translate("MainWindow", "量化回测参数优化"))
        self.dockWidget2.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.Navgiate1.setText(_translate("MainWindow", "&VNPY官网"))
        self.Navgiate2.setText(_translate("MainWindow", "&VNTrader官网"))
        self.Navgiate3.setText(_translate("MainWindow", "&VNPY知乎"))
        self.Navgiate4.setText(_translate("MainWindow", "&知乎视频"))
        self.Navgiate5.setText(_translate("MainWindow", "&期货低佣金开户"))
        self.Navgiate6.setText(_translate("MainWindow", "&量化资源列表"))
        self.Navgiate2.setToolTip(_translate("MainWindow", "submenu"))
        self.Navgiate1_C.setText(_translate("MainWindow", "一键平仓"))
        self.Button_OpenDll.setText(_translate("MainWindow", "&开启DLL数据显示"))
        self.Button_CloseDll.setText(_translate("MainWindow", "&关闭DLL数据显示"))
        self.Button_StrategyManage_SingleThread.setText(_translate("MainWindow", "&Python单线程管理(仅支持.py策略文件类型)"))
        self.Button_StrategyManage_MulitProcess.setText(
            _translate("MainWindow", "&C++多进程管理（支持.py和.dll策略文件类型）（暂不支持，等待更新）"))
        self.Button_KlineSource_RealTimeTick.setText(_translate("MainWindow", "&实时TICK生成K线"))
        self.Button_KlineSource_ServerToday.setText(_translate("MainWindow", "&实时TICK生成K线 + 从服务器补齐1日K线"))
        self.Button_KlineSource_ServerMultiday.setText(
            _translate("MainWindow", "&实时TICK生成K线 + 从服务器补齐多日K线（增值服务Plus会员激活）"))
        self.Navgiate1.triggered.connect(self.Function_OpenUrl_VNPY)
        self.Navgiate2.triggered.connect(self.Function_OpenUrl_VNTRADER)
        self.Navgiate3.triggered.connect(self.Function_OpenUrl_ZHIHU)
        self.Navgiate4.triggered.connect(self.Function_OpenUrl_ZHIHUVIDEO)
        self.Navgiate5.triggered.connect(self.Function_OpenUrl_KAIHU)
        self.Navgiate6.triggered.connect(self.Function_OpenUrl_COOLQUANT)
        self.Button_OpenDll.triggered.connect(self.Function_OpenDllLog)
        self.Button_CloseDll.triggered.connect(self.Function_CloseDllLog)
        self.Button_StrategyManage_SingleThread.triggered.connect(self.Function_EnableStrategyManage_SingleThread)
        self.Button_StrategyManage_MulitProcess.triggered.connect(self.Function_EnableStrategyManage_MulitProcess)
        self.Button_KlineSource_RealTimeTick.triggered.connect(self.Function_KlineSource_RealTimeTick)
        self.Button_KlineSource_ServerToday.triggered.connect(self.Function_KlineSource_ServerToday)
        self.Button_KlineSource_ServerMultiday.triggered.connect(self.Function_KlineSource_ServerMultiday)
        self.Button_Start.clicked.connect(self.OnStart)
        self.Button_Stop.clicked.connect(self.OnStop)
        # 策略说明按钮
        self.Button_StrategyInstructions.clicked.connect(self.Function_StrategyInstructions)
        self.Button_StrategyFunction.clicked.connect(self.Function_StrategyInstructions)
        # 添加合约组
        self.Button_AddInstrumentGroup.clicked.connect(self.Function_AddInstrumentGroup)
        # 关于合约组说明
        self.Button_AboutInstrumentGroup.clicked.connect(self.Function_AboutInstrumentGroup)
        # 添加投资者账户按钮
        self.Button_AddInvestor.clicked.connect(self.Function_AddInvestor)
        # 修改投资者账户按钮
        self.Button_ModifyInvestor.clicked.connect(self.Function_ModifyInvestor)
        # 注册SIMNOW账户
        self.Button_Simnow.clicked.connect(self.Function_OpenUrl_SIMNOW)
        # 开立实盘账户（低佣金开户，A级期货公司）
        self.Button_Kaihu.clicked.connect(self.Function_OpenUrl_KAIHU)
        # Plus会员说明
        self.Button_Plus.clicked.connect(self.Function_OpenUrl_Plus)
        # VNPY社区
        self.Button_Community.clicked.connect(self.Function_OpenUrl_Community)
        # 绑定期货账号
        self.Button_BandPlus.clicked.connect(self.Function_OpenUrl_BandPlus)
        # 购买Plus
        self.Button_Buyplus.clicked.connect(self.Function_OpenUrl_Buyplus)
        self.Button_SetServiceUser.clicked.connect(self.Function_OpenUrl_VNPY)
        self.Button_BuyService.clicked.connect(self.Function_OpenUrl_VNPY)
        self.Button_AddStrategy.clicked.connect(self.Function_ScanStrategy)
        self.Button_OpenStrategyPath.clicked.connect(self.Function_OpenStrategyPath)
        self.Button_ConditionCombination.clicked.connect(self.Function_Buttonclicke0)
        self.Button_TalibCondition.clicked.connect(self.Function_Buttonclicke0)
        self.Button_OpenAlgorithmicTradingPath.clicked.connect(self.Function_OpenAlgorithmicTradingPath)
        self.Button_OpenBackTestingPath.clicked.connect(self.Function_OpenBackTestingPath)
        self.Button_ClearTodayMdLog.clicked.connect(self.Function_ClearTodayMdLog)
        self.Button_ClearTodayTdLog.clicked.connect(self.Function_ClearTodayTdLog)
        self.Button_FaqDevelopmentEnvironment.clicked.connect(self.Function_FaqDevelopmentEnvironment)
        self.Button_FaqKaihu.clicked.connect(self.Function_FaqKAIHU)
        self.Function_ScanStrategy()
        self.Function_ScanInstrumentIDGroup()
        self.Function_ScanTDHistorylog()
        self.Function_ScanMDHistorylog()
        module_backtest.Function_ReadDataList(globalvar.ui.table_backtestdata, False)
